Thursday, January 6, 2011

Export to Excel using StreamWriter Interop

You need to impor:
using excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
 
//Variables
excel.Application App;
excel.Workbook WB;
excel.Worksheet wsheet;
excel.Range range;

//Open New Instance of Excel
App = new excel.Application();
App.Visible = true;
App.DisplayAlerts = false;

//New Workbook
WB = App.Workbooks.Add(Missing.Value);

//New Sheet
wsheet = (excel.Worksheet)WB.ActiveSheet;
wsheet.Name = "Hoja";

//Procces DataTable
int Aux = 1;
foreach (DataRow row in table.Rows)
{
     Aux+=1;
     for (int i = 1; i < table.Columns.Count + 1; i++)
     {
          //Add Headers
          if (Aux == 2)
          {
               wsheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
          }
          wsheet.Cells[Aux, i] = row[i - 1].ToString();
     }
}

No comments:

Post a Comment