簡體   English   中英

使用C#代碼將excel文件保存到csv文件

[英]Save an excel file to a csv file in C# code

我想打開一個excel文件並將其另存為csv文件。 谷歌搜索沒有幸運。 我需要C代碼才能做到這一點。

謝謝你的幫助。

如果您願意使用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!");
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();
        }
    }
}

您可以使用Visual Studio Tools for Office或ADO.NET來執行此操作。
為了獲得更多兼容性,我建議你使用第二個:看看David Hayden的一些教程,學習如何使用它。

要創建CSV文件,您只需閱讀Excel數據並使用Wikipedia中編寫的結構將結果寫入文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM