参考:

​http://www.codeproject.com/Articles/246772/Convert-xlsx-xls-to-csv​

​http://exceldatareader.codeplex.com/​


做法:从excel中把数据读取出来,然后每个单元格的值用逗号隔开,再拼起来,保存到一个.csv文件中。


using System.IO;
using Excel;
using System.Data;


需要引用 ExcelDataReader 开源项目 中的2个DLL: Excel.dll  和 ICSharpCode.SharpZipLib.dll

以下是只读取第一个 sheet 内容的样例。

public static bool ReadSheet1(string sXlsxFile,out string sError)
{
sError = "";

try
{
string filePath = sXlsxFile;
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);

Reading from a binary Excel file ('97-2003 format; *.xls)
//IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);

// Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);

// DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();

string sSheet1 = result.Tables[0].TableName.ToString(); // to get first sheet name (table name)

StringBuilder csvData = new StringBuilder();
int row_no = 0;
int ind = 0;

while (row_no < result.Tables[ind].Rows.Count) // ind is the index of table
// (sheet name) which you want to convert to csv
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData.Append(result.Tables[ind].Rows[row_no][i].ToString() + ",");
}
row_no++;
csvData.Append("\n");
}

string output = filePath.Replace(".xlsx", ".csv"); // define your own filepath & filename
StreamWriter csv = new StreamWriter(@output, false);
csv.Write(csvData);
csv.Close();

// Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
}
catch (Exception ex)
{
sError = ex.Message;
}

return sError.Trim() == "";
}


完整的代码下载:


    convert Excel file (xlsx, xls) to csv


TestExcel.zip


链接: ​​http://pan.baidu.com/s/1gdtJuyJ​​      ( 1.7MB ) 密码:qpkq      


(结束)