
using System; using System.IO; using System.Data; using System.Collections; using System.Data.OleDb; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Aspose.Cells; using NPOI.SS.UserModel; using System.Collections.Generic; using OfficeOpenXml; using OfficeOpenXml.Style; using System.Drawing; namespace Utils { /// <summary> /// Excel操作類(包括:HSSFWorkbook、OleDb、Aspose、EPPlus、HttpResponse) /// Spire.xls:http://www.cnblogs.com/landeanfen/p/5888973.html /// </summary> public class ExcelHelper { #region 讀取Excel數據到DataTable /// <summary> /// HSSFWorkbook讀取xls /// </summary> /// <param name="filepath">文件路徑</param> /// <returns></returns> public static DataTable GetExcelToDataTableByNPOI(string filepath) { NPOI.HSSF.UserModel.HSSFWorkbook hssworkbook; using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read)) { hssworkbook = new NPOI.HSSF.UserModel.HSSFWorkbook(file); } ISheet sheet = hssworkbook.GetSheetAt(0); IRow headerRow = sheet.GetRow(0); int rowCount = sheet.LastRowNum; int cellCount = headerRow.LastCellNum; DataTable dt = new DataTable(); for (int j = 0; j < cellCount; j++) { dt.Columns.Add(Convert.ToChar(((int)('A')) + j).ToString()); } for (int r = (sheet.FirstRowNum + 1); r <= rowCount; r++) { IRow row = sheet.GetRow(r); //讀取當前行數據 if (row != null) { DataRow dr = dt.NewRow(); cellCount = row.LastCellNum; bool isCellNull = true; for (int i = 0; i < cellCount; i++) { ICell cell = row.GetCell(i); if (cell == null) { dr[i] = ""; } else { cell.SetCellType(NPOI.SS.UserModel.CellType.String); dr[i] = cell.StringCellValue; if (isCellNull) { if (!string.IsNullOrWhiteSpace(cell.StringCellValue)) { isCellNull = false; } } } } if (!isCellNull) { dt.Rows.Add(dr); } } } return dt; } /// <summary> /// OleDb讀取xls/xlsx /// </summary> /// <param name="filepath">文件路徑</param> /// <returns></returns> public static DataTable GetExcelToDataTableByOleDb(string filepath) { string strCon = ""; if (filepath.IndexOf(".xlsx") != -1) strCon = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; else if (filepath.IndexOf(".xls") != -1) strCon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filepath + ";" + ";Extended Properties=\"Excel 8.0;HDR=YES;IMEX=1\""; string strCom = " SELECT * FROM [Sheet1$]"; DataTable dt_temp = new DataTable(); using (OleDbConnection myConn = new OleDbConnection(strCon)) using (OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn)) { myConn.Open(); myCommand.Fill(dt_temp); } return dt_temp; } /// <summary> /// Aspose讀取xls/xlsx /// </summary> /// <param name="filepath">文件路徑</param> /// <returns></returns> public static DataTable GetExcelToDataTableByAspose(string filepath) { DataTable dt_temp = new DataTable(); try { Aspose.Cells.Workbook oBook = new Aspose.Cells.Workbook(filepath); Cells cells = oBook.Worksheets[0].Cells; dt_temp = cells.ExportDataTable(0, 0, cells.MaxDataRow + 1, cells.MaxColumn + 1); } catch (Exception ex) { } return dt_temp; } #endregion #region 導出DataTable/List數據到Excel /// <summary> /// 直接導出到HttpResponse輸出流 /// </summary> /// <param name="dt">需要導出的DataTable</param> /// <param name="fileName">導出文件名稱</param> /// <param name="Title">表頭</param> public static void ExportToExcel(DataTable dt, string fileName, List<string> Title) { HttpResponse response = System.Web.HttpContext.Current.Response; ; response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ".xls"); Workbook workbook = new Workbook(); Worksheet sheet = (Worksheet)workbook.Worksheets[0]; int i = 0; foreach (var item in Title) { Aspose.Cells.Style s = new Aspose.Cells.Style(); s.Font.IsBold = true; sheet.Cells[0, i].PutValue(item); sheet.Cells[0, i].SetStyle(s); i++; } int RCount = dt.Rows.Count; int CCount = dt.Columns.Count; for (int x = 0; x < RCount; x++) { for (int y = 0; y < CCount; y++) { sheet.Cells[x + 1, y].PutValue(dt.Rows[x][y] + ""); } } response.Clear(); response.Buffer = true; response.ContentEncoding = System.Text.Encoding.UTF8; response.ContentType = "application/ms-excel"; response.BinaryWrite(workbook.SaveToStream().ToArray()); response.End(); } /// <summary> /// 直接導出到HttpResponse輸出流,並自定義文件名 /// </summary> public static void DataTableToExcel(DataTable dtData, String FileName) { GridView dgExport = null; HttpContext curContext = HttpContext.Current; StringWriter strWriter = null; HtmlTextWriter htmlWriter = null; if (dtData != null) { curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); curContext.Response.ContentType = "application nd.ms-excel"; curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; curContext.Response.Charset = "GB2312"; strWriter = new StringWriter(); htmlWriter = new HtmlTextWriter(strWriter); dgExport = new GridView(); dgExport.DataSource = dtData.DefaultView; dgExport.AllowPaging = false; dgExport.DataBind(); dgExport.RenderControl(htmlWriter); //curContext.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=gb2312\"/>" + strWriter.ToString()); // 自動返回可下載的文件流 curContext.Response.Write(strWriter.ToString()); curContext.Response.End(); } } /// <summary> /// Aspose導出數據到本地 /// </summary> /// <param name="dt">要導出的數據</param> /// <param name="tableName">表格標題</param> /// <param name="path">保存路徑</param> public static void ExportToExcelByAspose(DataTable dt, string tableName, string path) { Workbook workbook = new Workbook(); //工作簿 Worksheet sheet = workbook.Worksheets[0]; //工作表 Cells cells = sheet.Cells;//單元格 ////為標題設置樣式 //Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增樣式 //styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中 //styleTitle.Font.Name = "宋體";//文字字體 //styleTitle.Font.Size = 18;//文字大小 //styleTitle.Font.IsBold = true;//粗體 ////樣式2 //Style style2 = workbook.Styles[workbook.Styles.Add()];//新增樣式 //style2.HorizontalAlignment = TextAlignmentType.Center;//文字居中 //style2.Font.Name = "宋體";//文字字體 //style2.Font.Size = 14;//文字大小 //style2.Font.IsBold = true;//粗體 //style2.IsTextWrapped = true;//單元格內容自動換行 //style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; ////樣式3 //Style style3 = workbook.Styles[workbook.Styles.Add()];//新增樣式 //style3.HorizontalAlignment = TextAlignmentType.Center;//文字居中 //style3.Font.Name = "宋體";//文字字體 //style3.Font.Size = 12;//文字大小 //style3.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin; //style3.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin; //style3.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin; //style3.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin; int Colnum = dt.Columns.Count;//表格列數 int Rownum = dt.Rows.Count;//表格行數 //生成行1 標題行 //cells.Merge(0, 0, 1, Colnum);//合並單元格 //cells[0, 0].PutValue(tableName);//填寫內容 //cells[0, 0].SetStyle(styleTitle); //cells.SetRowHeight(0, 38); //生成行2 列名行 for (int i = 0; i < Colnum; i++) { cells[0, i].PutValue(dt.Columns[i].ColumnName); //cells[1, i].SetStyle(style2); cells.SetRowHeight(0, 25); } //生成數據行 for (int i = 0; i < Rownum; i++) { for (int k = 0; k < Colnum; k++) { cells[1 + i, k].PutValue(dt.Rows[i][k].ToString()); //cells[2 + i, k].SetStyle(style3); } cells.SetRowHeight(1 + i, 24); } workbook.Save(path); } /// <summary> /// EPPlus導出數據到本地 /// </summary> /// <param name="pathFileName"></param> /// <param name="IsPageRegistration"></param> /// <param name="SearchContent"></param> /// <param name="competitionId"></param> private void ExportToExcelByEPPlus(string pathFileName, DataTable dt) { //創建存放Excel的文件夾 FileInfo newFile = new FileInfo(pathFileName); if (newFile.Exists) { newFile.Delete(); newFile = new FileInfo(pathFileName); } //創建工作簿和工作表 using (ExcelPackage package = new ExcelPackage(newFile)) { ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("userInfo"); /*添加表頭*/ workSheet.InsertRow(1, 1); using (var range = workSheet.Cells[1, 1, 1, 6]) { range.Merge = true; range.Style.Font.SetFromFont(new System.Drawing.Font("Britannic Bold", 18, FontStyle.Italic)); range.Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous; range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228)); range.Style.Font.Color.SetColor(Color.Black); range.Value = "參賽者基本信息"; } /*設置標題*/ workSheet.Cells[2, 1].Value = "隊 別"; workSheet.Cells[2, 2].Value = "姓 名"; workSheet.Cells[2, 3].Value = "身份證號碼"; workSheet.Cells[2, 4].Value = "省 份"; workSheet.Cells[2, 5].Value = "城 市"; workSheet.Cells[2, 6].Value = "學 校"; using (var range = workSheet.Cells[2, 1, 2, 6]) { range.Style.Font.Bold = true; range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue); range.Style.Font.Color.SetColor(Color.White); range.AutoFilter = true; } /*設置單元格內容*/ int row = 3; foreach (DataRow pUser in dt.Rows) { workSheet.Cells[row, 1].Value = pUser[0]; workSheet.Cells[row, 2].Value = pUser[1]; workSheet.Cells[row, 3].Value = pUser[2]; workSheet.Cells[row, 4].Value = pUser[3]; workSheet.Cells[row, 5].Value = pUser[4]; workSheet.Cells[row, 6].Value = pUser[5]; row++; } /*添加表尾*/ using (var range = workSheet.Cells[dt.Rows.Count + 3, 1, dt.Rows.Count + 3, 6]) { range.Merge = true; range.Style.Font.SetFromFont(new System.Drawing.Font("Britannic Bold", 18, FontStyle.Italic)); range.Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous; range.Style.Fill.PatternType = ExcelFillStyle.Solid; range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(184, 204, 228)); range.Style.Font.Color.SetColor(Color.Black); range.Value = "總人數:" + dt.Rows.Count + "人"; } /*設置整個Excel樣式*/ workSheet.Cells[workSheet.Dimension.Address].AutoFitColumns(); workSheet.Cells[workSheet.Dimension.Address].Style.Border.Bottom.Style = ExcelBorderStyle.Thin; workSheet.Cells[workSheet.Dimension.Address].Style.Border.Right.Style = ExcelBorderStyle.Thin; workSheet.Cells[workSheet.Dimension.Address].Style.HorizontalAlignment = ExcelHorizontalAlignment.CenterContinuous; package.Save(); } } /// <summary> /// OLEDB將數據導出至Excel文件 /// </summary> /// <param name="Table">DataTable對象</param> /// <param name="Columns">要導出的數據列集合</param> /// <param name="ExcelFilePath">Excel文件路徑</param> public static bool ExportToExcelByOLEDB(DataTable Table, ArrayList Columns, string ExcelFilePath) { if (File.Exists(ExcelFilePath)) { throw new Exception("該文件已經存在!"); } //如果數據列數大於表的列數,取數據表的所有列 if (Columns.Count > Table.Columns.Count) { for (int s = Table.Columns.Count + 1; s <= Columns.Count; s++) { Columns.RemoveAt(s); //移除數據表列數后的所有列 } } //遍歷所有的數據列,如果有數據列的數據類型不是 DataColumn,則將它移除 DataColumn column = new DataColumn(); for (int j = 0; j < Columns.Count; j++) { try { column = (DataColumn)Columns[j]; } catch (Exception) { Columns.RemoveAt(j); } } if ((Table.TableName.Trim().Length == 0) || (Table.TableName.ToLower() == "table")) { Table.TableName = "Sheet1"; } //數據表的列數 int ColCount = Columns.Count; //創建參數 OleDbParameter[] para = new OleDbParameter[ColCount]; //創建表結構的SQL語句 string TableStructStr = @"Create Table " + Table.TableName + "("; //連接字符串 string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;"; OleDbConnection objConn = new OleDbConnection(connString); //創建表結構 OleDbCommand objCmd = new OleDbCommand(); //數據類型集合 ArrayList DataTypeList = new ArrayList(); DataTypeList.Add("System.Decimal"); DataTypeList.Add("System.Double"); DataTypeList.Add("System.Int16"); DataTypeList.Add("System.Int32"); DataTypeList.Add("System.Int64"); DataTypeList.Add("System.Single"); DataColumn col = new DataColumn(); //遍歷數據表的所有列,用於創建表結構 for (int k = 0; k < ColCount; k++) { col = (DataColumn)Columns[k]; //列的數據類型是數字型 if (DataTypeList.IndexOf(col.DataType.ToString().Trim()) >= 0) { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.Double); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " Double)"; } else { TableStructStr += col.Caption.Trim() + " Double,"; } } else { para[k] = new OleDbParameter("@" + col.Caption.Trim(), OleDbType.VarChar); objCmd.Parameters.Add(para[k]); //如果是最后一列 if (k + 1 == ColCount) { TableStructStr += col.Caption.Trim() + " VarChar)"; } else { TableStructStr += col.Caption.Trim() + " VarChar,"; } } } //創建Excel文件及文件結構 try { objCmd.Connection = objConn; objCmd.CommandText = TableStructStr; if (objConn.State == ConnectionState.Closed) { objConn.Open(); } objCmd.ExecuteNonQuery(); } catch (Exception exp) { throw exp; } //插入記錄的SQL語句 string InsertSql_1 = "Insert into " + Table.TableName + " ("; string InsertSql_2 = " Values ("; string InsertSql = ""; //遍歷所有列,用於插入記錄,在此創建插入記錄的SQL語句 for (int colID = 0; colID < ColCount; colID++) { if (colID + 1 == ColCount) //最后一列 { InsertSql_1 += Columns[colID].ToString().Trim() + ")"; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ")"; } else { InsertSql_1 += Columns[colID].ToString().Trim() + ","; InsertSql_2 += "@" + Columns[colID].ToString().Trim() + ","; } } InsertSql = InsertSql_1 + InsertSql_2; //遍歷數據表的所有數據行 DataColumn DataCol = new DataColumn(); for (int rowID = 0; rowID < Table.Rows.Count; rowID++) { for (int colID = 0; colID < ColCount; colID++) { //因為列不連續,所以在取得單元格時不能用行列編號,列需得用列的名稱 DataCol = (DataColumn)Columns[colID]; if (para[colID].DbType == DbType.Double && Table.Rows[rowID][DataCol.Caption].ToString().Trim() == "") { para[colID].Value = 0; } else { para[colID].Value = Table.Rows[rowID][DataCol.Caption].ToString().Trim(); } } try { objCmd.CommandText = InsertSql; objCmd.ExecuteNonQuery(); } catch (Exception exp) { string str = exp.Message; } } try { if (objConn.State == ConnectionState.Open) { objConn.Close(); } } catch (Exception exp) { throw exp; } return true; } #endregion } }