using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.Data; using System.Windows.Forms; using System.IO; using System.Data.OleDb; using System.Collections; /// ///使用該類 需要添加 NOPI.dll 的引用 ///版本為 2.0.0.0 namespace CommonClass { public static class ExcelHelper { #region 導出 /// <summary> /// 導出一個Datatable的數據到Excel文件 /// </summary> /// <param name="dt">需要導出的DataTable</param> public static void ExportDataTableToExcel(DataTable dt) { try { HSSFWorkbook wk = new HSSFWorkbook(); ISheet sheet = wk.CreateSheet("Sheet1"); int RowCount = dt.Rows.Count; int ColumnCount = dt.Columns.Count; IRow row = sheet.CreateRow(0); for (int j = 0; j < ColumnCount; j++) //列標題 { sheet.SetColumnWidth(j, 20 * 256); ICell cell = row.CreateCell(j); cell.SetCellType(CellType.STRING); cell.SetCellValue(dt.Columns[j].ColumnName); } for (int i = 0; i < RowCount; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < ColumnCount; j++) { sheet.SetColumnWidth(j, 20 * 256); ICell cell = row.CreateCell(j); cell.SetCellType(CellType.STRING); cell.SetCellValue(dt.Rows[i][j].ToString()); } } SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存為Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { using (FileStream fs = File.OpenWrite(dlg.FileName)) //打開一個xls文件,如果沒有則自行創建,如果存在文件則在創建是不要打開該文件! { wk.Write(fs); //向打開的這個xls文件中寫入Sheet1表並保存。 MessageBox.Show("導出成功!"); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// 導出一個DataGridView的數據到Excel文件 /// </summary> /// <param name="Gridview">綁定了數據源的DataGridView控件</param> public static void ExportDataGridViewToExcel(DataGridView Gridview) { HSSFWorkbook wk = new HSSFWorkbook(); ISheet sheet = wk.CreateSheet("Sheet1"); int RowCount = Gridview.RowCount; int ColumnCount = Gridview.ColumnCount; IRow row = sheet.CreateRow(0); for (int j = 0; j < ColumnCount; j++) //列標題 { sheet.SetColumnWidth(j, 20 * 256); ICell cell = row.CreateCell(j); cell.SetCellType(CellType.STRING); cell.SetCellValue(Gridview.Columns[j].HeaderText); } for (int i = 0; i < RowCount; i++) { row = sheet.CreateRow(i + 1); for (int j = 0; j < ColumnCount; j++) { sheet.SetColumnWidth(j, 20 * 256); ICell cell = row.CreateCell(j); cell.SetCellType(CellType.STRING); cell.SetCellValue(Gridview.Rows[i].Cells[j].Value.ToString()); } } SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Execl files (*.xls)|*.xls"; dlg.FilterIndex = 0; dlg.RestoreDirectory = true; dlg.CreatePrompt = true; dlg.Title = "保存為Excel文件"; if (dlg.ShowDialog() == DialogResult.OK) { using (FileStream fs = File.OpenWrite(dlg.FileName)) //打開一個xls文件,如果沒有則自行創建,如果存在文件則在創建是不要打開該文件! { wk.Write(fs); //向打開的這個xls文件中寫入Sheet1表並保存。 MessageBox.Show("導出成功!"); } } } #endregion #region 讀取 /// <summary> /// 讀取一個Excel文件(只讀取該文件的第一個Sheet的數據) /// </summary> /// <returns>返回一個包含Excel文件數據的DataTable</returns> public static DataTable ReadExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "讀取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("請選擇Excel文件!"); return dt; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } string sql = "SELECT * FROM [" + GetExcelFirstTableName(OpenDialog.FileName, connStr)[0].ToString() + "] "; con = new OleDbConnection(connStr); con.Open(); da = new OleDbDataAdapter(sql, con); da.Fill(ds); if (ds.Tables[0].Rows.Count == 0) { MessageBox.Show("選擇的文件沒數據!"); return dt; } else { dt = ds.Tables[0]; } return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); return dt; } } } return dt; } /// <summary> /// 讀取一個Excel文件(讀取該文件的所有Sheet的數據,但是該文件的所有Sheet數據格式必須一致) /// </summary> /// <returns>返回一個包含Excel文件數據的DataTable</returns> public static DataTable ReadMoreExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "讀取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("請選擇Excel文件!"); return dt; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } ArrayList sqllist = new ArrayList(); ArrayList tablelist = new ArrayList(); tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr); for (int i = 0; i < tablelist.Count; i++) { sqllist.Add("SELECT * FROM [" + tablelist[i] + "]"); } con = new OleDbConnection(connStr); con.Open(); for (int i = 0; i < sqllist.Count; i++) { da = new OleDbDataAdapter(sqllist[i].ToString(), con); da.Fill(ds); } if (ds.Tables[0].Rows.Count == 0) { MessageBox.Show("選擇的文件沒數據!"); return dt; } else { dt = ds.Tables[0]; } return dt; } catch (Exception ex) { MessageBox.Show(ex.Message); return dt; } } } return dt; } /// <summary> /// 讀取一個Excel文件(讀取該文件的所有Sheet的數據,該文件的Sheet數據格式可以一致) /// </summary> /// <returns>返回一個包含Excel文件數據的DataSet</returns> public static DataSet ReadMoreNotSameExcelToDataTable() { DataTable dt = new DataTable(); OpenFileDialog OpenDialog = new OpenFileDialog(); OpenDialog.Filter = "Excel Files|*.xls|Excel Files|*.xlsx"; OpenDialog.FilterIndex = 0; OpenDialog.RestoreDirectory = true; OpenDialog.Title = "讀取Excel文件"; OleDbConnection con; OleDbDataAdapter da; DataSet ds = new DataSet(); if (OpenDialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(OpenDialog.FileName)) { MessageBox.Show("請選擇Excel文件!"); return ds; } else { try { string filename = OpenDialog.FileName.Substring(OpenDialog.FileName.LastIndexOf('.')); string connStr = ""; switch (filename) { case ".xls": { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } case ".xlsx": { connStr = "Provider=Microsoft.Ace.OLEDB.12.0;data source=" + OpenDialog.FileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'"; break; } default: { connStr = "Provider=Microsoft.Jet.OLEDB.4.0;data source=" + OpenDialog.FileName + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; break; } } ArrayList sqllist = new ArrayList(); ArrayList tablelist = new ArrayList(); tablelist = GetExcelAllTableName(OpenDialog.FileName, connStr); for (int i = 0; i < tablelist.Count; i++) { sqllist.Add("SELECT * FROM [" + tablelist[i] + "]"); } con = new OleDbConnection(connStr); con.Open(); for (int i = 0; i < sqllist.Count; i++) { da = new OleDbDataAdapter(sqllist[i].ToString(), con); da.Fill(ds, "Table" + i); } bool isHave = false; for (int i = 0; i < ds.Tables.Count; i++) { if (ds.Tables[i].Rows.Count != 0) { isHave = true; } } if (!isHave) { MessageBox.Show("選擇的文件沒數據!"); return ds; } return ds; } catch (Exception ex) { MessageBox.Show(ex.Message); return ds; } } } return ds; } /// <summary> /// 獲取第一個Sheet的名稱 /// </summary> /// <param name="excelFileName">Excel文件名稱</param> /// <param name="strExtension">讀取Excel文件數據的數據連接</param> /// <returns></returns> private static ArrayList GetExcelFirstTableName(string excelFileName, string strExtension) { ArrayList tablenamelist = new ArrayList(); try { if (File.Exists(excelFileName)) { using (OleDbConnection conn = new OleDbConnection(strExtension)) { conn.Open(); DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); tablenamelist.Add(dt.Rows[0][2].ToString().Trim()); return tablenamelist; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return tablenamelist; } /// <summary> /// 獲取所有Sheet的名稱 /// </summary> /// <param name="excelFileName">Excel文件名稱</param> /// <param name="strExtension">讀取Excel文件數據的數據連接</param> /// <returns></returns> private static ArrayList GetExcelAllTableName(string excelFileName, string strExtension) { ArrayList tablenamelist = new ArrayList(); try { if (File.Exists(excelFileName)) { using (OleDbConnection conn = new OleDbConnection(strExtension)) { conn.Open(); DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); for (int i = 0; i < dt.Rows.Count; i++) { tablenamelist.Add(dt.Rows[i][2].ToString().Trim()); } return tablenamelist; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } return tablenamelist; } #endregion } }