Sérgio Ribeiro
Sérgio Ribeiro

Reputation: 51

How to generate Excel sheets with more than 1048576 rows

when I try to generate an excel file with more than 1048576 rows, I get the error:

System.ArgumentOutOfRangeException: Row number must be between 1 and 1048576>

How can I generate the excel file (currently I have an 7,000,000 rows query to export).

This is how I am generating the files:

public static byte[] ExportToExcel(IEnumerable<object> data, string sheetName)
    {

        if (data == null)
        {
            return null;
        }

        XLWorkbook wb = new XLWorkbook();

        var ws = wb.Worksheets.Add(sheetName);

        var columns = data.FirstOrDefault().GetType().GetProperties().ToList();

        var greyBackgroun = XLColor.FromHtml("#DDDDDD");

        for (var i = 0; i < columns.Count; i++)
        {
            ws.Row(1).Cell(i + 1).Value = columns[i].GetDisplayName();
            ws.Row(1).Cell(i + 1).Style.Font.SetBold(true);
            ws.Row(1).Cell(i + 1).Style.Fill.SetBackgroundColor(greyBackgroun);

        }

        ws.Cell(2, 1).InsertData(data).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
        ws.ColumnsUsed().AdjustToContents();
        ws.RowsUsed().AdjustToContents();

        using (MemoryStream memoryStream = new MemoryStream())
        {
            wb.SaveAs(memoryStream, false);
            return memoryStream.ToArray();
        }
    }

Upvotes: 0

Views: 1425

Answers (1)

S&#233;rgio Ribeiro
S&#233;rgio Ribeiro

Reputation: 51

Update:

Found out that Excel has a row limit (and it is 1048576). I'll just generate a bunch of files and zip them instead of generating one file with 7 milion rows.

Upvotes: 1

Related Questions