How to append a new row to an Excel file using C# and ClosedXML?

Vladislav Rudskoy picture Vladislav Rudskoy · Mar 21, 2015 · Viewed 13.2k times · Source

I should append a new row to an existing Excel file. The task consists of two parts:

  1. Add to non-existing file (works well).
  2. Add to existing file (doesn't work: it doesn't make NEW record, displaying only the old record from "else" body).

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?

Answer

Raidri supports Monica picture Raidri supports Monica · Mar 23, 2015

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();