C# 将 csv 转换为 xls(使用现有的 csv 文件)

标签 c# .net excel csv converters

我相信这里有很多关于这个问题的讨论。 但我阅读了所有帖子并尝试但它永远无法与 c# 一起使用。 我的目标很简单,我有现有的 csv 文件。 只想转换 exel 文件并完成。 很多人说使用 spire.xls 什么的,但我相信 MS .office.interop.excel 可以处理它。

Converting Excel File From .csv To .xlsx

我阅读了上面的问题,这与我的问题相同。 但上面的代码在我的电脑上不起作用..我需要导入其他 dll 才能使用它吗? 我只是从那个网站复制代码。在下面再次复制...

目前我正在使用 Lib 作为 MS.office.interop.excel 和 MS.office.interop.core

Application app = new Application();
Workbook wb = app.Workbooks.Open(@"C:\testcsv.csv", Type.Missing, Type.Missing,               Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.SaveAs(@"C:\testcsv.xlsx", XlFileFormat.xlOpenXMLWorkbook, Type.Missing,    Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
wb.Close();
app.Quit();

这里有很多错误。修改代码如下,现在我仅在引用中使用 MS.office.interop.excel 和 MS.office.interop.core。 看来我需要使用另一个 dll 文件。 无论如何,我确实遵循了该代码并编写了新代码。 它减少了错误,但我不知道这是正确的方法。 下面是我现在尝试的。

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;

System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Add(misValue);

xlWorkBook = xlApp.Workbooks.Open(@"C:\testcsv.csv", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.SaveAs(@"C:\testcsv.xlsx",    XlFileFormat.xlOpenXMLWorkbook, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(); 

这里是错误信息

Error 3 The name 'XlFileFormat' does not exist in the current context C:\Users\jochoi\Desktop\joseph_BT_전류_code\DC_Test - ver01\DC_Test\DC.cs 528 54 DC_Test
Error 4 The name 'XlSaveAsAccessMode' does not exist in the current context C:\Users\jochoi\Desktop\joseph_BT_전류_code\DC_Test - ver01\DC_Test\DC.cs 528 142 DC_Test
Error 4 No overload for method 'Close' takes '0' arguments C:\Users\jochoi\Desktop\joseph_BT_전류_code\DC_Test - ver01\DC_Test\DC.cs 525 13 DC_Test

我的目标只是抓取现有的 csv 文件并更改为 excel 文件。 有没有人有其他解决方案,因为那个答案在我的电脑上不起作用。 (c#)

最佳答案

COM Interop 不是最佳解决方案,尤其是当您计划在 server environment 中运行代码时。 .

Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.

另一种方法是使用适合该目的的组件。
我用过 EEplus它做了肮脏的工作。 它有 LGPL 许可证,但作者似乎不是 worried关于您在商业产品中使用它的信息。

只需安装 nuget 包:

Install-Package EPPlus

并使用这段代码:

using System.IO;
using OfficeOpenXml;

class Program
{
    static void Main(string[] args)
    {
        string csvFileName = @"FL_insurance_sample.csv";
        string excelFileName = @"FL_insurance_sample.xls";

        string worksheetsName = "TEST";

        bool firstRowIsHeader = false;

        var format = new ExcelTextFormat();
        format.Delimiter = ',';
        format.EOL = "\r";              // DEFAULT IS "\r\n";
        // format.TextQualifier = '"';

        using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName)))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
            worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
            package.Save();
        }

        Console.WriteLine("Finished!");
        Console.ReadLine();
    }
}

您可以使用 ExcelTextFormat 配置 CVS 的结构。

我已经使用从 here 中获取的一些数据对其进行了测试.

可以找到更多样本here .

更新:

另一种选择是自己读取 CSV 文件作为文本文件:

private IEnumerable<string[]> ReadCsv(string fileName, char delimiter = ';')
{
    var lines = System.IO.File.ReadAllLines(fileName, Encoding.UTF8).Select(a => a.Split(delimiter));
    return (lines);
}

并使用其他开源项目,例如 NPOIClosedXML . NPOIClosedXML 无法读取 CSV 并进行转换,但使用函数 ReadCsv 您可以自己完成。

这两个项目都有宽松的许可证。

NPOI 转化:

private static bool ConvertWithNPOI(string excelFileName, string worksheetName, IEnumerable<string[]> csvLines)
{
    if (csvLines == null || csvLines.Count() == 0)
    {
    return (false);
    }

    int rowCount = 0;
    int colCount = 0;

    IWorkbook workbook = new XSSFWorkbook();
    ISheet worksheet = workbook.CreateSheet(worksheetName);

    foreach (var line in csvLines)
    {
    IRow row = worksheet.CreateRow(rowCount);

    colCount = 0;
    foreach (var col in line)
    {
        row.CreateCell(colCount).SetCellValue(TypeConverter.TryConvert(col));
        colCount++;
    }
    rowCount++;
    }

    using (FileStream fileWriter = File.Create(excelFileName))
    {
       workbook.Write(fileWriter);
       fileWriter.Close();
    }

    worksheet = null;
    workbook = null;

    return (true);
}

ClosedXML 转换:

private static bool ConvertWithClosedXml(string excelFileName, string worksheetName, IEnumerable<string[]> csvLines)
{
    if (csvLines == null || csvLines.Count() == 0)
    {
    return (false);
    }

    int rowCount = 0;
    int colCount = 0;

    using (var workbook = new XLWorkbook())
    {
    using (var worksheet = workbook.Worksheets.Add(worksheetName))
    {
        rowCount = 1;
        foreach (var line in csvLines)
        {
        colCount = 1;
        foreach (var col in line)
        {
            worksheet.Cell(rowCount, colCount).Value = TypeConverter.TryConvert(col);
            colCount++;
        }
        rowCount++;
        }

    }
    workbook.SaveAs(excelFileName);
    }

    return (true);
}

如果有人感兴趣,请查看 sample project在 github 上对三种产品的性能进行了一些比较测试。

关于C# 将 csv 转换为 xls(使用现有的 csv 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648641/

相关文章:

c# - 是否有任何 .net 的 Web 浏览器引擎可以返回响应 cookie 及其路径?

java - 在Android上使用jxl修改excel电子表格

c# - 使用 SMO 还原对象还原差异备份

c# - Visual Studio 2008 办公室互操作 2003 与 2007

c# - async await 在调用异步方法时返回 Task<List<T>> 而不是 List<T>

vba - Excel VBA - Vlookup

excel - 在SSIS中从Excel导入数据,空值

c# - C# Dictionary 中的 KeyNotFoundException 在根据什么更改属性值后,计算 GetHashCode。为什么?

c# - 脱机时如何以编程方式查明本地文件是否受 TFS 版本控制

java - 自动化安装过程