分享

c# 读取excel文件的三种方法

 快乐至上365 2014-04-04

VS2010  读取excel文件的三种方法

方法一:NPOI 

 NPOI参考

优点:

NPOI 是 POI 项目的 .NET 版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。

使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 WORD/EXCEL 文档进行读写。

操作步骤:

一、下载NPOI:http://down./down?cid=DAEA322D9D7F934B898077FB01C3A8CB02A746E6

二、项目添加引用;

三、首先把如下代码封装成一个ExcelHelper类;

四、调用方法。

 

代码:(经测试)

    /// <summary>   
    /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable   
    /// </summary>   
    /// <param name="excelFileStream">Excel文件流</param>   
    /// <param name="headerRowIndex">Excel表头行索引</param>   
    /// <returns>DataSet</returns>   
    public static DataSet ImportDataSetFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
    {
       
        DataSet ds = new DataSet();
        HSSFWorkbook workbook = new HSSFWorkbook(excelFileStream);
        string sheetname = null;
        HSSFSheet sheet = null;
      
        try
        {
            sheetname = sheetName.Substring(0, sheetName.Length - 1);
            sheet = workbook.GetSheet(sheetname);//"BlankSubtraction1"

            if (sheet != null)
            {

                DataTable table = new DataTable();
                HSSFRow headerRow = sheet.GetRow(headerRowIndex);
                int cellCount = headerRow.LastCellNum;
                for (int i = headerRow.FirstCellNum; i < 20; i++)
                {
                    //string tst1 = headerRow.GetCell(1).ToString();
                    //string tst2 = headerRow.GetCell(1).StringCellValue.Trim();

                    if (headerRow.GetCell(i) != null)
                    {
                        //// 如果遇到第一个空列,则不再继续向后读取                   
                        //cellCount = i + 1;
                        //break;
                        DataColumn column = new DataColumn(i.ToString());
                        table.Columns.Add(column);
                    }
                    //DataColumn column = new DataColumn(i.ToString());//headerRow.GetCell(i).StringCellValue
                    //table.Columns.Add(column);
                }
                for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                {
                    HSSFRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        DataRow dataRow = table.NewRow();

                        cellCount = row.Cells.Count;

                        for (int j = row.FirstCellNum; j < 15; j++)
                        {
                            if (row.GetCell(j) != null)//row.GetCell(j) != null
                            {
                                string tst = row.GetCell(j).ToString();
                                dataRow[j] = row.GetCell(j).ToString();
                            }
                        }
                        table.Rows.Add(dataRow);
                    }
                }
                ds.Tables.Add(table);
            }           
        }
        catch
        {
 
        }
        excelFileStream.Close();
        workbook = null;
        return ds;
    }
    /// <summary>   
    /// 由Excel导入DataSet,如果有多个工作表,则导入多个DataTable   
    /// </summary>    /// <param name="excelFilePath">Excel文件路径,为物理路径。</param>   
    /// <param name="headerRowIndex">Excel表头行索引</param>   
    /// <returns>DataSet</returns>   
    public DataSet ImportDataSetFromExcel(string excelFilePath, string sheetName, int headerRowIndex)
    {
        using (FileStream stream = System.IO.File.OpenRead(excelFilePath))
        {
            long tt = stream.Length;
            //while (stream.Length() != null)
            int ss = stream.ReadByte();

            return ImportDataSetFromExcel(stream, sheetName, headerRowIndex);
        }
    }

 

方法二:使用COM组件。

缺点:

只能在安装excel 2003时才可以。

优点:(特殊情况下使用

使用于excel打开后需要点击“保存”才能用程序读取的情况。

操作步骤:

首先,在引用的COM中找到Microsoft Excel 11.0 Object Library,添加。

代码:(经测试)

public DataSet CSV_Getds(string filePath)
        {
            //创建Application对象
            Microsoft.Office.Interop.Excel.Application xApp = new Microsoft.Office.Interop.Excel.Application();


            xApp.Visible = false;//

            //得到WorkBook对象, 可以用两种方式之一: 下面的是打开已有的文件
            //Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(@"C:\Watson Data Interface\Raw Data\Thermo multiscan\吸光度值原始数据(450-630-blank).xls",
            //Missing.Value, Missing.Value, Missing.Value, Missing.Value
            //, Missing.Value, Missing.Value, Missing.Value, Missing.Value
            //, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            Microsoft.Office.Interop.Excel.Workbook xBook = xApp.Workbooks._Open(filePath,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value
            , Missing.Value, Missing.Value, Missing.Value, Missing.Value
            , Missing.Value, Missing.Value, Missing.Value, Missing.Value);
            //xBook=xApp.Workbooks.Add(Missing.Value);//新建文件的代码
            //指定要操作的Sheet,两种方式:

            Microsoft.Office.Interop.Excel.Worksheet xSheet = (Microsoft.Office.Interop.Excel.Worksheet)xBook.Sheets[1];
            //Worksheet ws = (Worksheet)xBook.Worksheets[1];

            //Excel.Worksheet xSheet=(Excel.Worksheet)xApp.ActiveSheet;

            //读取数据,通过Range对象
            //Microsoft.Office.Interop.Excel.Range rng1 = xSheet.get_Range("A1", Type.Missing);


            //读取,通过Range对象,但使用不同的接口得到Range
            //Microsoft.Office.Interop.Excel.Range rng2 = (Microsoft.Office.Interop.Excel.Range)xSheet.Cells[3, 1];


            //保存方式三
            xBook.Save();
            xBook.Close();
            xSheet = null;
            xBook = null;
            xApp.Quit(); //这一句是非常重要的,否则Excel对象不能从内存中退出
            xApp = null;

 

            //保存方式二:保存WorkSheet
            //xSheet.SaveAs(@"C:\Watson Data Interface\Raw Data\Thermo multiscan\吸光度值原始数据(450-630-blank).xls",
            //            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            //            Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);


            try
            {
                string[] name = GetTablesFromOleDb(filePath);
                string a = string.Empty;
                for (int i = 0; i < name.Length; i++)
                {
                    if (name[i].Replace("'", "") == "BlankSubtraction1$")//BlankSubtraction1
                    {
                        a = name[i].Replace("'", "");
                    }
                }
                if (a == string.Empty)//不存在BlankSubtraction1时取Photometric1
                {
                    for (int i = 0; i < name.Length; i++)
                    {
                        if (name[i].Replace("'", "") == "Photometric1$")
                        {
                            a = name[i].Replace("'", "");
                        }
                    }
                }

                string OLEDBConnStr = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filePath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";


                OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + a + "]", OLEDBConnStr);


                DataSet sourceDataTable = new DataSet();
                oda.Fill(sourceDataTable);
                oda.Dispose();


                GC.Collect();

                return sourceDataTable;


            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return null;
            }

        }

 

  /// <summary>
       /// 提供excel驱动和连接
       /// </summary>
       /// <param name="path"></param>
       /// <returns></returns>
        public static string[] GetTablesFromOleDb(string path)
        {

            string[] result = null;
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +
                                    "Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\";" + // 指定扩展属性为 Microsoft Excel 8.0 (97) 9.0 (2000) 10.0 (2002),并且第一行作为数据返回,且以文本方式读取
                                    "data source=" + path;
            OleDbConnection conn = null;
            System.Data.DataTable tblSchema = null;


            // 初始化连接,并打开
            conn = new OleDbConnection(connStr);
            try
            {
                conn.Open();
                tblSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
                result = new string[tblSchema.Rows.Count];
                for (int i = 0; i < tblSchema.Rows.Count; i++)
                {
                    result[i] = tblSchema.Rows[i][2].ToString();
                }
            }
            catch (Exception ex)
            {
                return null;
            }

            finally
            {
                // 关闭连接e
                conn.Close();
                conn.Dispose();
            }
            return result;
        }
      

方法三:使用office 驱动。

优点:

此方法最简单,也最普遍。

 

代码:(经测试)

        public DataSet CSV_Getds(string filePath)
        {
            try
            {
                string[] name = GetTablesFromOleDb(filePath);
                string a = string.Empty;
                for (int i = 0; i < name.Length; i++)
                {
                    if (name[i].Replace("'", "") == "BlankSubtraction1$")//BlankSubtraction1
                    {
                        a = name[i].Replace("'", "");
                    }
                }
                if (a == string.Empty)//不存在BlankSubtraction1时取Photometric1
                {
                    for (int i = 0; i < name.Length; i++)
                    {
                        if (name[i].Replace("'", "") == "Photometric1$")
                        {
                            a = name[i].Replace("'", "");
                        }
                    }
                }

                string OLEDBConnStr = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filePath + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";


                OleDbDataAdapter oda = new OleDbDataAdapter("select * from [" + a + "]", OLEDBConnStr);

                DataSet sourceDataTable = new DataSet();
                oda.Fill(sourceDataTable);
                oda.Dispose();


                GC.Collect();

                return sourceDataTable;

 

            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return null;
            }

        }

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多