CsvHelper.Excel icon indicating copy to clipboard operation
CsvHelper.Excel copied to clipboard

Write multiple sheets

Open ruslanss opened this issue 3 years ago • 2 comments

Is it possible to write multiple worksheets in a single file? I can't work out how to do it, tried this:

                using (FileStream fs = File.Create(fileName))
                {
                    ExcelWriter writer = null;
                    writer = new ExcelWriter(fs, "Sheet1", ci, true);
                    await writer.WriteRecordsAsync(data1);

                    writer = new ExcelWriter(fs, "Sheet2", ci, true);
                    await writer.WriteRecordsAsync(data2);

                    await writer.DisposeAsync();
                }

and end up with a workbook with a single sheet "Sheet2"

ruslanss avatar Jun 30 '21 12:06 ruslanss

Since this is based on CsvHelper, I would guess it isn't possible to do multi-sheet workbooks, but I agree that would be excellent if it could.

motoyugota avatar Sep 08 '21 18:09 motoyugota

You can make it work pretty easily if you copy the ExcelWriter to you project and add a new constructor that takes the Sheet instead of the stream:

 public XlsxWriter(IXLWorksheet sheet, CultureInfo currentCulture, int startRow = 1, int startColumn = 1)
            : this(sheet, new CsvConfiguration(currentCulture), startRow, startColumn)
        {
        }

        public XlsxWriter(IXLWorksheet sheet, CsvConfiguration configuration, int startRow = 1, int startColumn = 1)
            : base(null, configuration)
        {
            _sheet = sheet;
            row = startRow;
            this.startColumn = index = startColumn;

pynej avatar Jan 27 '23 23:01 pynej

Is this still not possible built-in? As @ruslanss mentioned initializing ExcelWriter with a different sheetName overwrites the default one. Any way to make it create a new sheet instead of overriding the existing one? Thanks

idkaltd avatar Jul 22 '24 14:07 idkaltd