.Net读取xlsx文件Excel2007
生活随笔
收集整理的這篇文章主要介紹了
.Net读取xlsx文件Excel2007
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
.NET 讀取Excel 2007的xlsx文件和讀取老的.xls文件是一樣的,都是用Oledb讀取,僅僅連接字符串不同而已。
讀取xlsx 用的是Microsoft.Ace.OleDb.12.0;
具體操作方法如下:
public static DataTable GetExcelToDataTableBySheet(string FileFullPath, string SheetName)
{//string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此連接只能操作Excel2007之前(.xls)文件string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件OleDbConnection conn = new OleDbConnection(strConn);conn.Open();DataSet ds = new DataSet();OleDbDataAdapter odda = new OleDbDataAdapter(string.Format("SELECT * FROM [{0}]", SheetName), conn); //("select * from [Sheet1$]", conn);odda.Fill(ds, SheetName);conn.Close();return ds.Tables[0];}讀取Excel文件時,可能一個文件中會有多個Sheet,因此獲取Sheet的名稱是非常有用的。具體操作方法如下://根據Excel物理路徑獲取Excel文件中所有表名public static String[] GetExcelSheetNames(string excelFile)
{OleDbConnection objConn = null;System.Data.DataTable dt = null;try{//string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + excelFile + ";Extended Properties='Excel 8.0; HDR=NO; IMEX=1'"; //此連接只能操作Excel2007之前(.xls)文件string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + excelFile + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'"; //此連接可以操作.xls與.xlsx文件objConn = new OleDbConnection(strConn);objConn.Open();dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);if (dt == null){return null;}String[] excelSheets = new String[dt.Rows.Count];int i = 0;foreach (DataRow row in dt.Rows){excelSheets[i] = row["TABLE_NAME"].ToString();i++;}return excelSheets;}catch{return null;}finally{if (objConn != null){objConn.Close();objConn.Dispose();}if (dt != null){dt.Dispose();}}
} 非常簡單就可以讀取到文件內容了,.NET就是強大。
命名空間:using System.IO;
返回路徑:StreamReader sr = new StreamReader(@"路徑", System.Text.Encoding.GetEncoding("GB18030")); //[設置中文編碼]
讀取文件:textBox1.Text = sr.ReadToEnd();
關閉流:sr.Close();
文章來自學IT網:http://www.xueit.com/html/2009-08/21_4340_00.html
命名空間:using System.IO;
返回路徑:StreamReader sr = new StreamReader(@"路徑", System.Text.Encoding.GetEncoding("GB18030")); //[設置中文編碼]
讀取文件:textBox1.Text = sr.ReadToEnd();
關閉流:sr.Close();
文章來自學IT網:http://www.xueit.com/html/2009-08/21_4340_00.html
轉載于:https://www.cnblogs.com/xiaofengfeng/archive/2010/08/27/1810032.html
總結
以上是生活随笔為你收集整理的.Net读取xlsx文件Excel2007的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]上下拉电阻
- 下一篇: IMX6ULL uboot启动分析(五)