读取文件将 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() == "";

        }

    

文章结束给大家分享下程序员的一些笑话语录: PC软件体积大,是因为一个PC软件功能往往较多,能够满足你一个方面的需求,而一个iphone软件往往没几行代码,干一件很小的事情,自然需要的软件就多。就像吃西瓜和吃瓜子的来比数目,单位不同啊。

你可能感兴趣的:(Excel)