I have been stuck with this problem for a while and cannot seem to find a way around it. I have read numerous articles on Stack Overflow yet nothing seems to answer my question. The tutorials I have followed as well all give different solutions but none seem to work.
I am trying to write data from a DataTable
into an excel spreadsheet. I am using Microsoft.Office.Interop.Excel
package and I do have Excel installed on my pc with admin rights.
At the top of my console app I have the following:
using Microsoft.Office.Interop.Excel;
I am using the following code to create the excel spreadsheet and populate it where dt
is the DataTable
:
var excel = new Application();
excel.Visible = false;
excel.DisplayAlerts = false;
var workBook = (Workbook)excel.Workbooks.Add(Type.Missing);
var workSheet = (Worksheet)workBook.ActiveSheet;
workSheet.Name = "Transformed Table";
for(int row = 0; row < dt.Rows.Count; row++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[row + 2, i + 1] = dt.Rows[row][i].ToString();
}
}
workBook.SaveAs("C:\\Users\\******\\Downloads\\test-file.xlsx");
workBook.Close();
excel.Quit();
The end result is an empty sheet.