Can I save an EXCEL worksheet as CSV via ClosedXML?

杀马特。学长 韩版系。学妹 提交于 2019-12-08 16:29:22

问题


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);
worksheet. /How to Save it as CSV?

回答1:


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>()))
 ));



回答2:


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




回答3:


Wrong in

row.LastCellUsed(false)

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




回答4:


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>()))
));


来源:https://stackoverflow.com/questions/27102904/can-i-save-an-excel-worksheet-as-csv-via-closedxml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!