Save an excel file to a csv file in C# code

前端 未结 3 1810
遇见更好的自我
遇见更好的自我 2020-12-06 18:09

I want to open an excel file and save it as a csv file. Google search no lucky. I need C sharp code to do it.

Thanks for your nice help.

相关标签:
3条回答
  • 2020-12-06 18:17

    You could use Visual Studio Tools for Office or ADO.NET to do this.
    For more compatibility I suggest you to use the second one: take a look at some tutorials like David Hayden's one to learn how to use it.

    To create a CSV file you have just to read the Excel data and write the results to a file using the structure written in Wikipedia.

    0 讨论(0)
  • 2020-12-06 18:23

    If you are willing to use 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!");
    
    0 讨论(0)
  • 2020-12-06 18:35
    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题