c#讀取excel的xls和xlsx檔案的方法
阿新 • • 發佈:2019-01-03
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(); }