Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

closedxml

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.

like image 676
Bigby Avatar asked Feb 10 '16 12:02

Bigby


1 Answers

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.

like image 198
Raidri Avatar answered Oct 04 '22 22:10

Raidri