将 Excel 文件 转换成 CSV 文件 解决方案

参考:

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      
     下载完成后的解压密码: http://blog.csdn.net/keenweiwei

(结束)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值