Can I save an EXCEL worksheet as CSV via ClosedXML?
Asked Answered
A

4

15

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?

Appal answered 24/11, 2014 at 10:42 Comment(0)
L
10

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>()))
 ));
Laurinelaurita answered 24/11, 2014 at 12:26 Comment(2)
All columns are write as single column.Rimose
Did you change the ";" to a "," It works for me when you do.Sofko
Q
23

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

Quincunx answered 23/5, 2017 at 18:32 Comment(1)
Bear in mind Excel cells can also contain the newline/return character, in which case they would also need quotes. There may be a couple of other trigger characters I'm not thinking of.Courbevoie
L
10

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>()))
 ));
Laurinelaurita answered 24/11, 2014 at 12:26 Comment(2)
All columns are write as single column.Rimose
Did you change the ";" to a "," It works for me when you do.Sofko
H
1

As @Emanuele points out, @Raidri's answer won't generate a proper CSV format, and it also omits blank rows entirely. To fix this:

var lastCellAddress = worksheet.RangeUsed().LastCell().Address;
System.IO.File.WriteAllLines(csvFileName, worksheet.Rows(1, lastCellAddress.RowNumber)
    .Select(row => String.Join(",", row.Cells(1, lastCellAddress.ColumnNumber)
        .Select(cell => cell.GetValue<string>()))
));
Harriman answered 6/3, 2017 at 0:17 Comment(0)
I
0

Wrong in

row.LastCellUsed(false)

it's not a correct format for csv. Last columns will be empty instead of get relative separator.

Invisible answered 2/7, 2015 at 7:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.