I should append a new row to an existing Excel file. The task consists of two parts:
Here is my code:
private static void ExportToEXCEL(DataTable dt, string paymentStoryPath)
{
if (File.Exists(paymentStoryPath))
{
XLWorkbook currentWorkbook = new XLWorkbook(paymentStoryPath);
IXLWorksheet currentWsh = currentWorkbook.Worksheet("Payment history");
//IXLCell cellForNewData = index.Cell(index.LastRowUsed().RowNumber() + 1, 1);
IXLRow rowForNewData = currentWsh.Row(currentWsh.LastRowUsed().RowNumber()+1);
rowForNewData.InsertRowsBelow(1);
rowForNewData.Value = dt;
currentWorkbook.Save();
}
else
{
//not exist
XLWorkbook wb = new XLWorkbook();
wb.Worksheets.Add(dt, "Payment history");
wb.SaveAs(paymentStoryPath);
}
}
What is wrong and what should I change in my code?
To add a DataTable
use the InsertTable()
method:
XLWorkbook currentWorkbook = new XLWorkbook(paymentStoryPath);
IXLWorksheet currentWsh = currentWorkbook.Worksheet("Payment history");
IXLCell cellForNewData = currentWsh.Cell(currentWsh.LastRowUsed().RowNumber() + 1, 1);
cellForNewData.InsertTable(dt);
currentWorkbook.Save();