[英]C# - Saving an excel file as CSV without using Interop.Excel
我的问题在于Microsoft.Office.Interop.Excel
。 我想摆脱对它的引用,因为它需要在您运行引用 .dll 的特定代码段的机器上安装 Excel。
这实际上意味着我已经开始使用 EPPlus 修改 Excel 个文件、工作簿、工作表等......
EPPlus 具有保存到 .csv 的功能,但仅从版本 5 开始,需要付费许可证。 出于预算原因,我不会购买该许可证,因此会继续使用以前版本的 EPPlus。
但是,这意味着我没有方便的方法将 Excel 文件 (xslx) 保存为 csv。
谁能告诉我一种在不使用 Interop.Excel 的情况下将 excel 工作表保存为 CSV 的方法
我维护了几个可以帮助解决这个问题的免费开源库: Sylvan.Data.Csv和Sylvan.Data.Excel 。
使用这些库可以轻松地将 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);
如果性能是一个问题,这些库也是 .NET 生态系统中执行各自任务最快的库。
我相信另一种选择是使用 NPOI 库在不使用 Interop 的情况下读取 Excel 个文件。
有关此库的更多详细信息,请访问: https://github.com/do.netcore/NPOI
这是一个非常简单的使用 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.