Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any simple way to convert .xls file to .csv file? (Excel)

Tags:

c#

csv

excel

Is there any simple way to convert .xls file to .csv file ? (Excel)

in C# code ?

i mean to take an existing .xls file and convert them to .csv file

Thanks in advance

like image 246
Gold Avatar asked Mar 29 '10 06:03

Gold


People also ask

How do you quickly convert XLS to CSV?

Press F5 key, select the folder contains the Excel files you want to convert to CSV files in first popping dialog. 5. Click OK, then in the second popping dialog, select the folder to place the CSV files.

Can I convert XLXS to CSV?

How to convert a XLSX to a CSV file? Choose the XLSX file that you want to convert. Select CSV as the the format you want to convert your XLSX file to. Click "Convert" to convert your XLSX file.


2 Answers

Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber parameter. You can overload the method if you need to support earlier versions.

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();       }    } } 
like image 166
mattmc3 Avatar answered Sep 19 '22 23:09

mattmc3


Checkout the .SaveAs() method in Excel object.

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

Or following:

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); } 
like image 44
KMån Avatar answered Sep 19 '22 23:09

KMån