Can I save an EXCEL worksheet as CSV via ClosedXML?

pencilCake picture pencilCake · Nov 24, 2014 · Viewed 9.7k times · Source

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?

Answer

Aivan Monceller picture Aivan Monceller · May 23, 2017

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