Excel 链接字符串sql
string xlsConnFormat = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='{0}';Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
一、HDR表示要把第一行做为数据仍是做为列名,做为数据用HDR=NO,做为列名用HDR=YES;数据库
二、经过IMEX=1来把混合型做为文本型读取,避免null值。ide
注意:把一个 Excel 文件看作一个数据库,一个sheet看作一张表。语法 "SELECT * FROM [sheet1$]",表单要使用"[]"和"$"。sqlserver
使用 OLEDB 读取不一样版本 Excel 数据的链接字符串设置ui
用OLEDB经过设置链接字符串能够像读取sqlserver同样将excel中的数据读取出来,可是excel2003和excel2007/2010的链接字符串是不一样的 。spa
/// <summary> /// 把数据从Excel装载到DataTable /// </summary> /// <param name="pathName">带路径的Excel文件名</param> /// <param name="sheetName">工做表名</param> /// <param name="tbContainer">将数据存入的DataTable</param> /// <returns></returns> public DataTable ExcelToDataTable(string pathName, string sheetName) { DataTable tbContainer = new DataTable(); string strConn = string.Empty; if (string.IsNullOrEmpty(sheetName)) { sheetName = "Sheet1"; } FileInfo file = new FileInfo(pathName); if (!file.Exists) { throw new Exception("文件不存在"); } string extension = file.Extension; switch (extension) { case ".xls": strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; case ".xlsx": strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; default: strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; break; } //连接Excel OleDbConnection cnnxls = new OleDbConnection(strConn); //读取Excel里面有 表Sheet1 OleDbDataAdapter oda = new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), cnnxls); DataSet ds = new DataSet(); //将Excel里面有表内容装载到内存表中! oda.Fill(tbContainer); return tbContainer; }
读取Excel文件时,可能一个文件中会有多个Sheet,所以获取Sheet的名称是很是有用的。excel
//根据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(); } } }