Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I save an EXCEL worksheet as CSV via ClosedXML?

Is it possible to save a worksheet of a workbook as CSV via ClosedXML?

For example:

var workbook = new XLWorkbook(fileName);
IXLWorksheet worksheet;
workbook.Worksheets.TryGetWorksheet(sheetName, out worksheet);

How to Save it as CSV?

like image 295
pencilCake Avatar asked Nov 24 '14 10:11

pencilCake


2 Answers

Other answers will fail to generate a valid CSV if cells have the separator so here is a better way

var lastCellAddress = worksheet.RangeUsed().LastCell().Address;
File.WriteAllLines(csvFileName, worksheet.Rows(1, lastCellAddress.RowNumber)
    .Select(r => string.Join(",", r.Cells(1, lastCellAddress.ColumnNumber)
            .Select(cell =>
        {
            var cellValue = cell.GetValue<string>();
            return cellValue.Contains(",") ? $"\"{cellValue}\"" : cellValue;
        }))));

This is based on @Extragorey's answer

like image 167
Aivan Monceller Avatar answered Oct 26 '22 16:10

Aivan Monceller


No, it is not possible directly in ClosedXML. You have to use loops or LINQ to build your own CSV file.

For example:

System.IO.File.WriteAllLines(csvFileName,
    worksheet.RowsUsed().Select(row =>
        string.Join(";", row.Cells(1, row.LastCellUsed(false).Address.ColumnNumber)
                            .Select(cell => cell.GetValue<string>()))
 ));
like image 31
Raidri Avatar answered Oct 26 '22 15:10

Raidri