最近遇到一個Excel導入導出的問題,要支持winform和webform,這裏我是一個認真嚴謹的coder,因此決定把這個記錄下來!和你們一塊兒分享一下!若是須要的同窗能夠下載哦! web
對於NPOI這個組件,你們可能都瞭解了吧!若是不瞭解的同窗,仍是百度一下吧!否則後面不太看懂的。 小程序
1.我封裝了這個類(ExcelHelper),該有的註釋我也都加上了,但願你們能夠看得懂!若是有什麼bug,能夠反饋到個人郵箱:707055073@qq.com 數組
本身作了一個簡單的winform的小程序,主要就是Excel的導入和導出,你們能夠下載看一下 安全
方法解釋說明 xss
ExcelToDataTable()--Excel轉換成DataTable--B/S和C/S均可以使用ide
ExcelToDataTable()--根據索引讀取Sheet表數據,默認讀取第一個sheet--B/S和C/S均可以使用測試
DataGridViewToExcel()--DataGridView導出到Excel文件--C/Sspa
#region ExcelToDataTable(string strExcelFileName, string strSheetName) Excel轉換成DataTable--B/S和C/S均可以使用 /// <summary> /// Excel轉換成DataTable /// </summary> /// <param name="strExcelFileName">文件路徑</param> /// <param name="strSheetName">Excel中對應的sheet表單名稱,如:sheet1,sheet2</param> /// <returns>數據集</returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2100:檢查 SQL 查詢是否存在安全漏洞")] public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName) { string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties=Excel 5.0;"; string strExcel = string.Format("select * from [{0}$]", strSheetName); DataSet ds = new DataSet(); using (OleDbConnection conn = new OleDbConnection(strConn)) { conn.Open(); OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn); adapter.Fill(ds, strSheetName); conn.Close(); return ds.Tables[strSheetName]; } } #endregion #region DataTable ExcelToDataTable(string strFileName, int sheetIndex = 0) 根據索引讀取Sheet表數據,默認讀取第一個sheet--B/S和C/S均可以使用 /// <summary>讀取excel /// 根據索引讀取Sheet表數據,默認讀取第一個sheet /// </summary> /// <param name="strFileName">excel文檔路徑</param> /// <param name="sheetIndex">sheet表的索引,從0開始</param> /// <returns>數據集</returns> public static DataTable ExcelToDataTable(string strFileName, int sheetIndex = 0) { DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook = null; XSSFWorkbook xssfworkbook = null; string fileExt = Path.GetExtension(strFileName);//獲取文件的後綴名 using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { if (fileExt == ".xls") hssfworkbook = new HSSFWorkbook(file); else if (fileExt == ".xlsx") xssfworkbook = new XSSFWorkbook(file);//初始化太慢了,不知道這是什麼bug } if (hssfworkbook != null) { HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(sheetIndex); if (sheet != null) { System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { HSSFCell cell = (HSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } } } else if (xssfworkbook != null) { XSSFSheet xSheet = (XSSFSheet)xssfworkbook.GetSheetAt(sheetIndex); if (xSheet != null) { System.Collections.IEnumerator rows = xSheet.GetRowEnumerator(); XSSFRow headerRow = (XSSFRow)xSheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { XSSFCell cell = (XSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (xSheet.FirstRowNum + 1); i <= xSheet.LastRowNum; i++) { XSSFRow row = (XSSFRow)xSheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } } } return dt; } #endregion #region DataGridViewToExcel(DataGridView myDgv, string strHeaderText, string strFileName) DataGridView導出到Excel文件--C/S /// <summary> /// C/S Winform中DataGridView導出數據到Excel /// </summary> /// <param name="myDgv">DataGridView控件名稱</param> /// <param name="saveFileName">保存的文件名稱,默認沒有,調用的時候最好加上,中英文都支持</param> /// <param name="isOpen">導出後是否打開文件和所在文件夾</param> /// <param name="saveFilePath">默認保存在「個人文檔」中,可自定義保存的文件夾路徑</param> /// <param name="strHeaderText">Excel中第一行的標題文字,默認沒有,能夠自定義</param> /// <param name="titleNames">Excel中列名的數組,默認綁定GridView的列名</param> public static void DataGridViewToExcel(DataGridView myDgv, string saveFileName = null, bool isOpen = false, string saveFilePath = null, string strHeaderText = null, string[] titleNames = null) { using (MemoryStream ms = DataGridViewToExcel(myDgv, strHeaderText, titleNames)) { if (string.IsNullOrEmpty(saveFileName)) //文件名爲空 { saveFileName = DateTime.Now.Ticks.ToString(); } if (string.IsNullOrEmpty(saveFilePath) || !System.IO.Directory.Exists(saveFilePath)) //保存路徑爲空或者不存在 { saveFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); //默認在文檔文件夾中 } string saveFullPath = saveFilePath + "\\" + saveFileName + ".xls"; if (System.IO.File.Exists(saveFullPath)) //驗證文件重複性 { saveFullPath = saveFilePath + "\\" + saveFileName + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace(":", "-").Replace(" ", "-") + ".xls"; } using (FileStream fs = new FileStream(saveFullPath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } if (isOpen) { Process.Start(saveFullPath); //打開文件 Process.Start(saveFilePath); //打開文件夾 } } } #endregion
添加引用包.net
Dll下載地址(http://download.csdn.net/detail/mryanghenglian/6873605) excel
這個壓縮文件當中包含了須要添加的dll和ExcelHelper類,添加完畢後,就可使用了,支持B/S和C/S的導入導出哦!但願你們能夠喜歡
測試程序項目下載地址
http://download.csdn.net/detail/mryanghenglian/6873615
小夥伴們若是以爲好,幫忙推薦一下!
*****************************************************************
未來的你必定會感激如今拼命的本身