2010-03-29 5 views

Trả lời

21

Thanh toán phương pháp .SaveAs() trong đối tượng Excel.

wbWorkbook.SaveAs("c:\yourdesiredFilename.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSV) 

Hoặc sau:

public static void SaveAs() 
{ 
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing); 
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets; 
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1]; 

    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1]; 

    thisCell.Value2 = "This is a test."; 

    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 

    wbWorkbook.Close(false, "", true); 
} 
+1

cảm ơn đối với sự giúp đỡ, nhưng làm thế nào tôi có thể chuyển đổi một tập tin hiện hành? – Gold

+0

Trong trường hợp bạn vẫn còn thắc mắc, bạn sẽ cần mở tệp hiện có làm sổ làm việc đầu tiên bằng phương thức Excel.Application.Workbooks.Open() và sử dụng nó làm tham số wbWorkbook – markdigi

+1

sử dụng xlSaveAsAccessMode.xlNoChange là đáng tin cậy hơn (cuộc gọi để SaveAs bị lỗi trong trường hợp của tôi nếu tôi sử dụng xlShared). – Benlitz

22

Dưới đây là một phương pháp C# để làm điều này. Hãy nhớ thêm xử lý lỗi của riêng bạn - điều này chủ yếu giả định rằng mọi thứ hoạt động vì lợi ích ngắn gọn. Đó là 4.0+ framework, nhưng đó chủ yếu là do tham số worksheetNumber tùy chọn. Bạn có thể quá tải phương thức nếu bạn cần hỗ trợ các phiên bản trước đó.

static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) { 
    if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath); 
    if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile); 

    // connection string 
    var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath); 
    var cnn = new OleDbConnection(cnnStr); 

    // get schema, then data 
    var dt = new DataTable(); 
    try { 
     cnn.Open(); 
     var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); 
     if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet"); 
     string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", ""); 
     string sql = String.Format("select * from [{0}]", worksheet); 
     var da = new OleDbDataAdapter(sql, cnn); 
     da.Fill(dt); 
    } 
    catch (Exception e) { 
     // ??? 
     throw e; 
    } 
    finally { 
     // free resources 
     cnn.Close(); 
    } 

    // write out CSV data 
    using (var wtr = new StreamWriter(csvOutputFile)) { 
     foreach (DataRow row in dt.Rows) { 
     bool firstLine = true; 
     foreach (DataColumn col in dt.Columns) { 
      if (!firstLine) { wtr.Write(","); } else { firstLine = false; } 
      var data = row[col.ColumnName].ToString().Replace("\"", "\"\""); 
      wtr.Write(String.Format("\"{0}\"", data)); 
     } 
     wtr.WriteLine(); 
     } 
    } 
} 
+0

Điều này làm việc cho tôi với một tệp XLSM. Cảm ơn bạn! –

0

Tôi cần làm điều tương tự. Tôi đã kết thúc với một cái gì đó tương tự như Kman

 static void ExcelToCSVCoversion(string sourceFile, string targetFile) 
    { 
     Application rawData = new Application(); 

     try 
     { 
      Workbook workbook = rawData.Workbooks.Open(sourceFile); 
      Worksheet ws = (Worksheet) workbook.Sheets[1]; 
      ws.SaveAs(targetFile, XlFileFormat.xlCSV); 
      Marshal.ReleaseComObject(ws); 
     } 

     finally 
     { 
      rawData.DisplayAlerts = false; 
      rawData.Quit(); 
      Marshal.ReleaseComObject(rawData); 
     } 


     Console.WriteLine(); 
     Console.WriteLine($"The excel file {sourceFile} has been converted into {targetFile} (CSV format)."); 
     Console.WriteLine(); 
    } 

Nếu có nhiều tờ này bị mất trong việc chuyển đổi nhưng bạn có thể lặp qua số tờ và tiết kiệm mỗi người như csv.

0

Cài đặt các gói 2

<packages> 
    <package id="ExcelDataReader" version="3.3.0" targetFramework="net451" /> 
    <package id="ExcelDataReader.DataSet" version="3.3.0" targetFramework="net451" /> 
</packages> 

chức năng Helper

using ExcelDataReader; 
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace ExcelToCsv 
{ 
    public class ExcelFileHelper 
    { 
     public static bool SaveAsCsv(string excelFilePath, string destinationCsvFilePath) 
     { 

      using (var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
      { 
       IExcelDataReader reader = null; 
       if (excelFilePath.EndsWith(".xls")) 
       { 
        reader = ExcelReaderFactory.CreateBinaryReader(stream); 
       } 
       else if (excelFilePath.EndsWith(".xlsx")) 
       { 
        reader = ExcelReaderFactory.CreateOpenXmlReader(stream); 
       } 

       if (reader == null) 
        return false; 

       var ds = reader.AsDataSet(new ExcelDataSetConfiguration() 
       { 
        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration() 
        { 
         UseHeaderRow = false 
        } 
       }); 

       var csvContent = string.Empty; 
       int row_no = 0; 
       while (row_no < ds.Tables[0].Rows.Count) 
       { 
        var arr = new List<string>(); 
        for (int i = 0; i < ds.Tables[0].Columns.Count; i++) 
        { 
         arr.Add(ds.Tables[0].Rows[row_no][i].ToString()); 
        } 
        row_no++; 
        csvContent += string.Join(",", arr) + "\n"; 
       } 
       StreamWriter csv = new StreamWriter(destinationCsvFilePath, false); 
       csv.Write(csvContent); 
       csv.Close(); 
       return true; 
      } 
     } 
    } 
} 

Cách sử dụng:

var excelFilePath = Console.ReadLine(); 
string output = Path.ChangeExtension(excelFilePath, ".csv"); 
ExcelFileHelper.SaveAsCsv(excelFilePath, output);