使用C#代码将excel文件保存到csv文件

ard*_*ore 5 .net c#

我想打开一个excel文件并将其另存为csv文件.谷歌搜索没有幸运.我需要C代码才能做到这一点.

谢谢你的帮助.

Joh*_*ner 10

如果您愿意使用Excel Interop:

        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!");
Run Code Online (Sandbox Code Playgroud)


小智 5

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


as-*_*cii -3

您可以使用 Visual Studio Tools for Office 或 ADO.NET 来执行此操作。
为了获得更多兼容性,我建议您使用第二个:查看一些教程(例如David Hayden 的教程)以了解如何使用它。

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