.NET 读取Excel 2007的xlsx文件和读取老的.xls文件是一样的,都是用Oledb读取,仅仅连接字符串不同而已。 读取xlsx 用的是Microsoft.Ace.OleDb.12.0; 具体操作方法如下: public static DataTable GetExcelToDataTableBySheet( string FileFullPath, string SheetName) { string strConn = "Provider=Microsoft.Ace.OleDb.12.0;" + "data source=" + FileFullPath + ";Extended Properties='Excel 12.0; HDR=NO; IMEX=1'" ; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataSet ds = new DataSet(); OleDbDataAdapter odda = new OleDbDataAdapter( string .Format( "SELECT * FROM [{0}]" , SheetName), conn); odda.Fill(ds, SheetName); conn.Close(); return ds.Tables[0]; } 老的xls就很简单,只是注意是Jet,还有ver是8.0 ResultInfo<List<HighEndNetFinancialEntity>> Result = new ResultInfo<List<HighEndNetFinancialEntity>>(); string ver = ""; int pos = FilePath.LastIndexOf(".") + 1; string postFileName = FilePath.Substring(pos, FilePath.Length - pos); if (postFileName == "xls") { ver = "8.0"; }
else { Result.Message = "请上传Exel-xls文件。"; Result.IsSuccess = false; return Result; }
DataSet result = null;
string strConn = "Provider=Microsoft.<span style="color:#ff0000;">Jet</span>.OLEDB.4.0;" + "Data Source=" + FilePath + ";" + "Extended Properties=\"Excel " + ver + ";IMEX=1\""; OleDbConnection conn = new OleDbConnection(strConn); try { conn.Open(); string strExcel = "select * from [sheet1$]"; OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn); result = new DataSet(); myCommand.Fill(result, "MFMui"); } catch (Exception e) { if (e != null) { Result.Message += e.Message; return Result; } } finally { conn.Close(); }
|