1 #region-----EXCELデータを読み込む----- 2 /// <summary> 3 /// EXCELデータを読み込む 4 /// </summary> 5 /// <param name="filePath"></param> 6 /// <returns></returns> 7 private System.Data.DataTable ExcelToDataTable(string filePath) 8 { 9 //ファイル拡張子 10 string fileType = System.IO.Path.GetExtension(filePath); 11 if (string.IsNullOrEmpty(fileType)) return null; 12 13 //Excel対象 14 myExcel.Application excel = new Excel.Application(); 15 excel.Application.EnableEvents = false; 16 17 //Workbook対象 18 myExcel.Workbook workbook = excel.Workbooks._Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 19 //Worksheet対象 20 myExcel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1]; 21 22 //シート名 23 string strSheetName = worksheet.Name; 24 string sql_F = "SELECT * FROM [" + strSheetName + "$]"; 25 26 //连接对象 27 OleDbConnection conn = null; 28 //读取数据对象 29 OleDbDataAdapter da = null; 30 //读取excel数据的dataset 31 System.Data.DataSet dsItem = new System.Data.DataSet(); 32 33 int nDBErrorFlag = 0; 34 //连接参数 35 string connStr = ""; 36 try 37 { 38 //Provider → Excel 97-2003,Excel 2007 39 //HDR=YES第一行是标题,NO第一行不是标题;IMEX=1表示导入模式,这个模式开启的 Excel 档案只能用来做“写入”用途,还有个重要作用:强制将混合数据转换为文本,可读出excel的数字型的内容。 40 connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=‘" + filePath + "‘;Extended Properties=‘Excel 12.0;HDR=Yes;IMEX=1‘"; 41 conn = new OleDbConnection(connStr); 42 conn.Open(); 43 44 da = new OleDbDataAdapter(sql_F, conn); 45 da.Fill(dsItem, strSheetName); 46 } 47 catch (Exception ex) 48 { 49 nDBErrorFlag = 1; 50 } 51 52 if (nDBErrorFlag == 1) 53 { 54 nDBErrorFlag = 0; 55 try 56 { 57 //Provider → Excel 97-2003 58 connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=‘" + filePath + "‘;Extended Properties=‘Excel 8.0;HDR=Yes;IMEX=1‘"; 59 conn = new OleDbConnection(connStr); 60 conn.Open(); 61 da = new OleDbDataAdapter(sql_F, conn); 62 63 dsItem = new System.Data.DataSet(); 64 da.Fill(dsItem, strSheetName); 65 } 66 catch (Exception ex) 67 { 68 throw (ex); 69 } 70 } 71 72 if (conn.State == ConnectionState.Open) 73 { 74 conn.Close(); 75 da.Dispose(); 76 conn.Dispose(); 77 } 78 return dsItem.Tables[strSheetName]; 79 } 80 #endregion
参考:https://www.cnblogs.com/goodgirlmia/p/3793200.html(【c#操作office】--OleDbDataAdapter 与OleDbDataReader方式读取excel,并转换为datatable)
https://www.cnblogs.com/wx881208/p/4096728.html (Excel的 OleDb 连接串的格式(Provider=Microsoft.ACE.OLEDB))
https://www.cnblogs.com/vaevvaev/p/6873367.html(C#连接OleDBConnection数据库的操作)
https://www.cnblogs.com/fengduandeai/p/8575494.html(System.IO.Path 文件名、路径、扩展名处理)
原文地址:https://www.cnblogs.com/-jwj/p/10710331.html
时间: 2024-11-08 10:05:33