I did a class on C# to open Excel with a DataTable:
var excelApp = new ExcelInterop.Application();
excelApp.Workbooks.Add();
ExcelInterop._Worksheet workSheet = excelApp.ActiveSheet;
for (int i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[1, (i + 1)] = dt.Columns[i].ColumnName;
}
ExcelRecursive(dt, workSheet, 0, 0);
excelApp.Visible = true;
The method recursive:
public void ExcelRecursive(DataTable dt, ExcelInterop._Worksheet ws, int i, int j)
{
ws.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
if (j + 1 < dt.Columns.Count)
ExcelRecursive(dt, ws, i, j + 1);
else if (i + 1 < dt.Rows.Count)
ExcelRecursive(dt, ws, i + 1, 0);
}
DataTables with 70 rows it's work very well, but more then that the application stopped and on console show an error 'Access Violation':
The program '[3396] iisexpress.exe: Program Trace' has exited with code 0 (0x0).
The program '[3396] iisexpress.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.
I try this:
for (int i = 0; i < dt.Rows.Count; i++)
{
// to do: format datetime values before printing
for (int j = 0; j < dt.Columns.Count; j++)
{
workSheet.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
}
}
And this:
public ExcelInterop._Worksheet ExcelRecursive(DataTable dt, ExcelInterop._Worksheet ws, int i, int j)
{
ws.Cells[(i + 2), (j + 1)] = dt.Rows[i][j];
if (j + 1 < dt.Columns.Count)
return ExcelRecursive(dt, ws, i, j + 1);
else if (i + 1 < dt.Rows.Count)
return ExcelRecursive(dt, ws, i + 1, 0);
else
return ws;
}
But my code only works on little DataTables