ClosedXML - Add a new row without overwrite data (first line)

Bigby picture Bigby · Feb 10, 2016 · Viewed 12.3k times · Source

I'm trying to add an empty row before filling my excel document.

using (DataTable dt = new DataTable())
{
    sda.Fill(dt);

    using (XLWorkbook wb = new XLWorkbook())
    {
        var ws = wb.Worksheets.Add(dt, "Report");
        var listOfStrings = new List<String>();
        ws.Cell(1, 6).Value = "Service";
        ws.Cell(1, 15).Value = "Invoice";

        ws.Range("A1:L1").Style.Fill.BackgroundColor = XLColor.DarkBlue;
        ws.Range("M1:Q1").Style.Fill.BackgroundColor = XLColor.DarkCandyAppleRed;
        ws.Range("M2:Q2").Style.Fill.BackgroundColor = XLColor.Red;

        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=Report.xlsx");

        using (MemoryStream MyMemoryStream = new MemoryStream())
        {
            wb.SaveAs(MyMemoryStream);
            MyMemoryStream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }
}

I only need to make the first row empty and then fill the document with my data. But all time I'm overwriting the document.

Answer

Raidri supports Monica picture Raidri supports Monica · Feb 10, 2016

To insert one row above the first row in the worksheet use this:

ws.Row(1).InsertRowsAbove(1);
                       // ^ number of rows to insert

There is also the method InsertRowsBelow() to insert new rows below a certain row. See the documentation for more examples.