【问题标题】:Save an excel file to a csv file in C# code在 C# 代码中将 excel 文件保存到 csv 文件
【发布时间】:2016-05-26 14:44:37
【问题描述】:

我想打开一个 excel 文件并将其保存为 csv 文件。谷歌搜索不走运。 我需要 C 语言代码来做到这一点。

感谢您的帮助。

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    如果您愿意使用 Excel 互操作:

            Excel.Application app = new Excel.Application();
            Excel.Workbook wb = app.Workbooks.Open(@"c:\temp\testtable.xlsx");
            wb.SaveAs(@"C:\Temp\output.csv", Excel.XlFileFormat.xlCSVWindows);
            wb.Close(false);
            app.Quit();
            Console.WriteLine("Done!");
    

    【讨论】:

    • 错误:方法“SaveAs”没有重载需要“2”个参数
    • 您使用了哪个 Excel 互操作库?您正在使用哪个 VS 版本以及正在编译的框架?根据这些答案,您可能需要传递所有参数,其余参数为 Type.Missing 以使其编译。
    • 这很好用;在实际代码中可能值得确保转换后的 csv 文件是唯一的……例如,使用 Guid 是创建唯一文件名的有效方法。
    【解决方案2】:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.Office.Interop.Excel;
    using System.IO;
    
    namespace TestConsoleApp
    {
        class Program
        {
            static void Main(string[] args)
            {
                String fromFile = @"C:\ExlTest\Test.xlsx";
                String toFile = @"C:\ExlTest\csv\Test.csv";
    
                Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
                Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(fromFile, 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);
    
                // this does not throw exception if file doesnt exist
                File.Delete(toFile);
    
                wb.SaveAs(toFile, Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Microsoft.Office.Interop.Excel.XlSaveConflictResolution.xlLocalSessionChanges, false, Type.Missing, Type.Missing, Type.Missing);
    
                wb.Close(false,Type.Missing,Type.Missing);
    
                app.Quit();
            }
        }
    }
    

    【讨论】:

    • VS2010 Office.Interop.Excel (v12)。这也适用于 .xls 文件。可能存在多个填充工作表的问题,仅使用具有单个工作表的工作簿进行测试。
    • File.Delete(toFile); 在 csv 文件不存在时会抛出错误
    【解决方案3】:

    您可以使用 Visual Studio Tools for Office 或 ADO.NET 来执行此操作。
    为了更好的兼容性,我建议你使用第二个:看看一些教程,比如David Hayden's 一个来学习如何使用它。

    要创建 CSV 文件,您只需读取 Excel 数据并将结果写入使用Wikipedia 中编写的结构的文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-06
      • 2017-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2021-11-21
      • 1970-01-01
      相关资源
      最近更新 更多