public class HExcel { #region 導入表格 /// <summary> /// 讀取Excel文件,內容存儲在DataSet中 /// </summary> /// <param name="fileName">文件路徑</param> /// <param name="sSelect">選擇語句{"A:F"表示選擇A到F列,包含A,F列, "A1:B2"表示選擇A1到B2范圍,包括A1,B2}</param> /// <param name="bTitle">是否將第一行作為標題行,如果是則可以采用 dr["天津"] 的形式讀取數據,否則采取dr[0]的形式</param> /// <returns></returns> public static DataTable ToDataSet(string fileName, string sSelect, bool bTitle) { //HDR=Yes,這代表第一行是標題,不做為數據使用 ,如果用HDR=NO,則表示第一行不是標題,做為數據來使用。系統默認的是YES //IMEX有3個值:當IMEX=2 時,EXCEL文檔中同時含有字符型和數字型時,比如第C列有3個值,2個為數值型 123,1個為字符型 ABC,當導入時, //頁面不報錯了,但庫里只顯示數值型的123,而字符型的ABC則呈現為空值。當IMEX=1時,無上述情況發生,庫里可正確呈現 123 和 ABC. string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=" + (bTitle ? "YES" : "NO") + ";IMEX=1\""; var conn = new OleDbConnection(strConn); string strExcel = string.Format(@"select * from [sheet1${0}]", sSelect); var ds = new DataSet(); try { conn.Open(); var xlsCommand = new OleDbDataAdapter(strExcel, strConn); xlsCommand.Fill(ds, "sheet1$"); } catch (Exception) { return null; } finally { conn.Close(); conn.Dispose(); } if (ds.Tables.Count > 0 && ds.Tables[0].Rows != null && ds.Tables[0].Rows.Count > 0) return ds.Tables[0]; return null; } #endregion #region ExportToExcel:導出excel /// <summary> /// 將DataTable轉成Excel[Table]字符串. 可用於直接輸出. /// </summary> /// <param name="dt">傳入的DataTable數據, 必須提供標題!</param> /// <returns></returns> public static string DTToExcelStr(DataTable dt) { string newLine = "<table cellspacing=\"1\" border=\"1\">"; newLine += "<tr><td colspan=\"" + dt.Columns.Count + "\" align=\"center\">" + dt.TableName + "</td></tr>"; newLine += "<tr>"; for (int i = 0; i < dt.Columns.Count; i++) { newLine += "<td>" + dt.Columns[i].Caption + "</td>"; } newLine += "</tr>"; for (int j = 0; j < dt.Rows.Count; j++) { newLine += "<tr>"; for (int i = 0; i < dt.Columns.Count; i++) { newLine += "<td>" + dt.Rows[j][i] + "</td>"; } newLine += "</tr>"; } newLine += "</table>"; return newLine; } /// <summary> /// 將DataTable導出到excel文件 /// </summary> /// <param name="dt">DataTable數據源</param> /// <param name="sFilePath">Excel文件路徑</param> /// <returns></returns> public static bool DTToExcelFile(DataTable dt, string sFilePath) { return HFile.Write(sFilePath, DTToExcelStr(dt)); } #endregion }