简体   繁体   English

C# - 在不使用 Interop 的情况下将 excel 文件保存为 CSV.Excel

[英]C# - Saving an excel file as CSV without using Interop.Excel

My issue lies with Microsoft.Office.Interop.Excel .我的问题在于Microsoft.Office.Interop.Excel I would like to get rid of references to it, because it requires an install of Excel on the machine that you're running a particular piece of code that references the.dll.我想摆脱对它的引用,因为它需要在您运行引用 .dll 的特定代码段的机器上安装 Excel。

What this means in practice is that I have started using EPPlus to modify Excel files, workbooks, worksheets, etc...这实际上意味着我已经开始使用 EPPlus 修改 Excel 个文件、工作簿、工作表等......

EPPlus has functionality to save to.csv, but only starting from version 5, which requires a paid license. EPPlus 具有保存到 .csv 的功能,但仅从版本 5 开始,需要付费许可证。 For budgetary reasons, I will not be purchasing that license, and therefore be staying at a previous version of EPPlus.出于预算原因,我不会购买该许可证,因此会继续使用以前版本的 EPPlus。

Though, this means that I have no convenient way of saving an Excel file (xslx) as csv.但是,这意味着我没有方便的方法将 Excel 文件 (xslx) 保存为 csv。

Can anybody tell me a way of saving an excel sheet as CSV without using Interop.Excel谁能告诉我一种在不使用 Interop.Excel 的情况下将 excel 工作表保存为 CSV 的方法

I maintain a couple free and open source libraries that can help with this: Sylvan.Data.Csv and Sylvan.Data.Excel .我维护了几个可以帮助解决这个问题的免费开源库: Sylvan.Data.CsvSylvan.Data.Excel

Converting from Excel to CSV is trivial using these libraries.使用这些库可以轻松地将 Excel 转换为 CSV。

using Sylvan.Data.Csv;
using Sylvan.Data.Excel;

using var excelReader = ExcelDataReader.Create(@"data.xlsx");
using var csvWriter = CsvDataWriter.Create("data.csv");
csvWriter.Write(excelReader);

If performance is a concern, these libraries are also the fastest libraries in the .NET ecosystem for their respective tasks..如果性能是一个问题,这些库也是 .NET 生态系统中执行各自任务最快的库。

I believe another alternative is to use the NPOI library to read Excel files without using Interop.我相信另一种选择是使用 NPOI 库在不使用 Interop 的情况下读取 Excel 个文件。

More details about this library you can find at: https://github.com/do.netcore/NPOI有关此库的更多详细信息,请访问: https://github.com/do.netcore/NPOI

Here is a very simple example of using NPOI, I used StreamWriter to save the CSV file and FileStream to get the XLSX file in this example:这是一个非常简单的使用 NPOI 的例子,我在这个例子中使用 StreamWriter 来保存 CSV 文件和 FileStream 来获取 XLSX 文件:

using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;

string csvSeparator = ";";
string filePath = @"{XLXS file path}";
StreamWriter sw = new StreamWriter(@"{CSV file path}", true);

using (var file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
    string strExt = System.IO.Path.GetExtension(filePath);

    IWorkbook wb;

    #region Check extension to define the Workbook
    if (strExt.Equals(".xls"))
    {
        wb = new HSSFWorkbook(file);
    }
    else
    {
        wb = new XSSFWorkbook(file);
    }
    #endregion

    ISheet sheet = wb.GetSheetAt(0);//Start reading at index 0

    for (int i = 0; i <= sheet.LastRowNum; i++)//Row
    {
        IRow row = sheet.GetRow(i);

        for (int j = 0; j < row.LastCellNum; j++)//Column
        {
            ICell cell = row.GetCell(j);

            object cellValue = null;

            #region Check cell type in order to define its value type
            switch (cell.CellType)
            {
                case CellType.Blank:
                case CellType.Error:
                    cellValue = null;
                    break;
                case CellType.Boolean:
                    cellValue = cell.BooleanCellValue;
                    break;
                case CellType.Numeric:
                    cellValue = cell.NumericCellValue;
                    break;
                case CellType.String:
                    cellValue = cell.StringCellValue;
                    break;
                default:
                    cellValue = cell.StringCellValue;
                    break;
            }
            #endregion

            sw.Write(cellValue.ToString());//Write the cell value
            sw.Write(csvSeparator);//Add the CSV separator
        }
        sw.Write(Environment.NewLine);//Add new line
    }
    sw.Flush();
    sw.Close();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM