将Excel文件(XLS或XLSX)转换为CSV文件 [英] Convert excel file (xls or xlsx) to csv file
本文介绍了将Excel文件(XLS或XLSX)转换为CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用此代码C#来处理excel 2003和2007版本的文件.
I need this code C# working for files excel 2003 and 2007 version.
我无法使用此C#代码在CSV文件上转换Excel文件(xls).
I can't get this C# code working to convert excel file (xls) on csv file.
如果尝试使用excel文件扩展名xlsx
都可以,但是如果尝试使用扩展名xls
我在此行中有错误:
If try with excel file extension xlsx
it's all ok but if try with extension xls
I have error in this line:
result.Tables[0].TableName.ToString();
我下面的代码,怎么了?
My code below, what's wrong?
代码隐藏
FileUploadControl.SaveAs(Server.MapPath("/public/") + filename);
System.IO.FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
Excel.IExcelDataReader excelReader = Excel.ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.Close();
result.Tables[0].TableName.ToString();
string csvData = "";
int row_no = 0;
int ind = 0;
while (row_no < result.Tables[ind].Rows.Count)
{
for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
{
csvData += result.Tables[ind].Rows[row_no][i].ToString() + ",";
}
row_no++;
csvData += "\n";
}
keys = GetUniqueKey(8).ToUpper();
output = System.Web.HttpContext.Current.Server.MapPath("/public/target_" + keys.ToString() + ".csv");
StreamWriter csv = new StreamWriter(@output, false);
csv.Write(csvData);
csv.Close();
推荐答案
Excel可以有两种类型:
Excel can be of two types:
- 二进制-Excel 2003及更早版本-
xls
- 邮政编码-基于Open Office XML标准-从Excel 2007开始-
xlsx
- Binary - Excel 2003 and older -
xls
- Zip - based on Open Office XML standards - Excel 2007 onwards -
xlsx
对于较旧的excel格式文件,您应该尝试使用以下内容:
You should try to use following for older excel format files:
ExcelReaderFactory.CreateBinaryReader(stream);
这篇关于将Excel文件(XLS或XLSX)转换为CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文