C# NOPI實現匯出 類
阿新 • • 發佈:2019-01-09
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using NPOI.SS.Util; namespace WebApplicationNopi { public class ExcelHelper { private static MemoryStream WriteToStream(HSSFWorkbook hssfworkbook) { //Write the stream data of workbook to the root directory MemoryStream file = new MemoryStream(); hssfworkbook.Write(file); return file; } //Export(DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle) /// <summary> /// 向客戶端輸出檔案。 /// </summary> /// <param name="table">資料表。</param> /// <param name="headerText">頭部文字。</param> /// <param name="sheetName"></param> /// <param name="columnName">資料列名稱。</param> /// <param name="columnTitle">表標題。</param> /// <param name="fileName">檔名稱。</param> public static void Write(HttpContext context, DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle, string fileName) { context.Response.Clear(); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); //HttpUtility.UrlEncode(fileName)); context.Response.ContentType = "application/vnd.ms-excel"; HSSFWorkbook hssfworkbook = new HSSFWorkbook(); GenerateData(hssfworkbook, table, headerText, sheetName, columnName, columnTitle); context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer()); context.Response.End(); } /// <summary> /// 向客戶端輸出檔案 /// </summary> /// <param name="context"></param> /// <param name="list">資料表列表</param> /// <param name="headerText">頭部文字</param> /// <param name="sheetNameList">資料列名稱集合</param> /// <param name="columnName">表標題集合</param> /// <param name="columnTitle">表標題集合</param> /// <param name="fileName">檔名稱</param> public static void Write(HttpContext context, List<DataTable> list, string headerText, string[] sheetNameList, List<string[]> columnName, List<string[]> columnTitle, string fileName) { context.Response.Clear(); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName); //HttpUtility.UrlEncode(fileName)); context.Response.ContentType = "application/vnd.ms-excel"; HSSFWorkbook hssfworkbook = new HSSFWorkbook(); for (int i = 0; i < sheetNameList.Length; i++) { GenerateData(hssfworkbook, list[i], headerText, sheetNameList[i], columnName[i], columnTitle[i]); } context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer()); context.Response.End(); } /// <summary> /// /// </summary> /// <param name="table"></param> /// <param name="headerText"></param> /// <param name="sheetName"></param> /// <param name="columnName"></param> /// <param name="columnTitle"></param> /// <returns></returns> public static HSSFWorkbook GenerateData(HSSFWorkbook hssfworkbook, DataTable table, string headerText, string sheetName, string[] columnName, string[] columnTitle) { //HSSFWorkbook hssfworkbook = new HSSFWorkbook(); ISheet sheet = hssfworkbook.CreateSheet(sheetName); #region 設定檔案屬性資訊 //建立一個文件摘要資訊實體。 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "Net"; //公司名稱 hssfworkbook.DocumentSummaryInformation = dsi; //建立一個摘要資訊實體。 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Subject = "本文件由 JINS OA系統生成"; si.Author = "licao"; si.Title = headerText; si.Subject = headerText; si.CreateDateTime = DateTime.Now; hssfworkbook.SummaryInformation = si; #endregion 設定檔案屬性資訊 ICellStyle dateStyle = hssfworkbook.CreateCellStyle(); IDataFormat format = hssfworkbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("@"); #region 取得列寬 int[] colWidth = new int[columnName.Length]; for (int i = 0; i < columnName.Length; i++) { colWidth[i] = Encoding.GetEncoding(936).GetBytes(columnTitle[i]).Length; } for (int i = 0; i < table.Rows.Count; i++) { for (int j = 0; j < columnName.Length; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(table.Rows[i][columnName[j]].ToString()).Length; if (intTemp > colWidth[j]) { colWidth[j] = intTemp; } } } #endregion 取得列寬 int rowIndex = 0; foreach (DataRow row in table.Rows) { #region 新建表,填充表頭,填充列頭,樣式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = hssfworkbook.CreateSheet(sheetName + ((int)rowIndex / 65535).ToString()); } #region 表頭及樣式 //if (!string.IsNullOrEmpty(headerText)) //{ // IRow headerRow = sheet.CreateRow(0); // headerRow.HeightInPoints = 25; // headerRow.CreateCell(0).SetCellValue(headerText); // ICellStyle headStyle = hssfworkbook.CreateCellStyle(); // headStyle.Alignment = HorizontalAlignment.Center; // IFont font = hssfworkbook.CreateFont(); // font.FontHeightInPoints = 20; // font.Boldweight = 700; // headStyle.SetFont(font); // headerRow.GetCell(0).CellStyle = headStyle; // //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); // sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, table.Columns.Count - 1)); //} #endregion 表頭及樣式 #region 列頭及樣式 { IRow headerRow = sheet.CreateRow(0); ICellStyle headStyle = hssfworkbook.CreateCellStyle(); headStyle.Alignment = HorizontalAlignment.Center; IFont font = hssfworkbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); for (int i = 0; i < columnName.Length; i++) { headerRow.CreateCell(i).SetCellValue(columnTitle[i]); headerRow.GetCell(i).CellStyle = headStyle; //設定列寬 if ((colWidth[i] + 1) * 256 > 30000) { sheet.SetColumnWidth(i, 10000); } else { sheet.SetColumnWidth(i, (colWidth[i] + 1) * 256); } } /* foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = headStyle; //設定列寬 sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } * */ } #endregion 列頭及樣式 if (!string.IsNullOrEmpty(headerText)) { rowIndex = 1; } else { rowIndex = 2; } } #endregion 新建表,填充表頭,填充列頭,樣式 #region 填充資料 IRow dataRow = sheet.CreateRow(rowIndex); for (int i = 0; i < columnName.Length; i++) { ICell newCell = dataRow.CreateCell(i); string drValue = row[columnName[i]].ToString(); switch (table.Columns[columnName[i]].DataType.ToString()) { case "System.String"://字串型別 if (drValue.ToUpper() == "TRUE") newCell.SetCellValue("是"); else if (drValue.ToUpper() == "FALSE") newCell.SetCellValue("否"); newCell.SetCellValue(drValue); break; case "System.DateTime"://日期型別 //DateTime dateV; //DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(drValue); newCell.CellStyle = dateStyle;//格式化顯示 break; case "System.Boolean"://布林型 bool boolV = false; bool.TryParse(drValue, out boolV); if (boolV) newCell.SetCellValue("是"); else newCell.SetCellValue("否"); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值處理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion 填充資料 rowIndex++; } return hssfworkbook; } /// <summary> /// 匯入Excel /// </summary> /// <param name="filePath"></param> public static DataTable Import(string filePath) { HSSFWorkbook workbook = OpenWorkbook(filePath); HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); DataTable dt = new DataTable(); if (sheet.LastRowNum <= 0) { return dt; } int lastCellNum = sheet.GetRow(0).LastCellNum; //新增列 if (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; for (int j = 0; j < lastCellNum; j++) { HSSFCell cell = (HSSFCell)row.GetCell(j); if (cell == null) { continue; } dt.Columns.Add(cell.ToString()); } } //新增行 while (rows.MoveNext()) { HSSFRow row = (HSSFRow)rows.Current; DataRow dr = dt.NewRow(); bool isChecked = false; for (int i = 0; i < row.LastCellNum; i++) { if (i >= dt.Columns.Count) { break; } HSSFCell cell = (HSSFCell)row.GetCell(i); if (cell == null || string.IsNullOrEmpty(cell.ToString())) { dr[i] = null; } else { isChecked = true; //數字型 if (cell.CellType == CellType.Numeric) { dr[i] = cell.NumericCellValue; } //字串型 else { dr[i] = cell.ToString(); } } } if (isChecked) { dt.Rows.Add(dr); } else { dr = null; } } return dt; } public static HSSFWorkbook OpenWorkbook(String fileName) { try { return new HSSFWorkbook(new FileStream(fileName, FileMode.Open)); } catch (IOException) { throw; } } public static HSSFWorkbook ExportDT(DataTable dtSource, string strHeaderText) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet; sheet.DefaultColumnWidth = 2; sheet.DefaultRowHeight = 15 * 20; #region 右擊檔案 屬性資訊 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "aaa"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "licao"; //填加xls檔案作者資訊 si.ApplicationName = "網銀"; //填加xls檔案建立程式資訊 si.LastAuthor = "licao"; //填加xls檔案最後儲存者資訊 si.Subject = "本文件由 JINS OA 系統生成"; //填加檔案主題資訊 si.CreateDateTime = DateTime.Now; workbook.SummaryInformation = si; } #endregion 右擊檔案 屬性資訊 HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle; HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat; dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd HH:mm:ss"); //取得列寬 int[] arrColWidth = new int[dtSource.Columns.Count]; foreach (DataColumn item in dtSource.Columns) { arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } for (int i = 0; i < dtSource.Rows.Count; i++) { for (int j = 0; j < dtSource.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow row in dtSource.Rows) { #region 新建表,填充表頭,填充列頭,樣式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workbook.CreateSheet() as HSSFSheet; } #region 表頭及樣式 { HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow; headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle; headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; HSSFFont font = workbook.CreateFont() as HSSFFont; font.FontHeightInPoints = 20; font.FontName = "宋體"; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); //headerRow.Dispose(); } #endregion 表頭及樣式 #region 列頭及樣式 { HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow; headerRow.Height = 15 * 20; HSSFCellStyle cellStyle = workbook.CreateCellStyle() as HSSFCellStyle; cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; HSSFFont font = workbook.CreateFont() as HSSFFont; font.FontHeightInPoints = 9; font.FontName = "宋體"; cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; cellStyle.FillBackgroundColor = HSSFColor.Blue.Index2; font.Boldweight = 700; cellStyle.SetFont(font); foreach (DataColumn column in dtSource.Columns) { headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); headerRow.GetCell(column.Ordinal).CellStyle = cellStyle; if ((arrColWidth[column.Ordinal] + 1) * 256 > 30000) { sheet.SetColumnWidth(column.Ordinal, 10000); } else { sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); } //設定列寬 } //headerRow.Dispose(); } #endregion 列頭及樣式 rowIndex = 2; } #endregion 新建表,填充表頭,填充列頭,樣式 #region 填充內容 HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow; foreach (DataColumn column in dtSource.Columns) { HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; string drValue = row[column].ToString(); switch (column.DataType.ToString()) { //case "System.String": //字串型別 // double result; // if (isNumeric(drValue, out result)) // { // double.TryParse(drValue, out result); // newCell.SetCellValue(result); // break; // } // else // { // newCell.SetCellValue(drValue); // break; // } case "System.DateTime": //日期型別 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle; //格式化顯示 break; case "System.Boolean": //布林型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull": //空值處理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(drValue); break; } } #endregion 填充內容 rowIndex++; } return workbook; } /// <summary> /// DataTable匯出到Excel檔案 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文字</param> /// <param name="strFileName">儲存位置</param> //public static void Write(HttpContext context, DataTable dtSource, string strHeaderText, string strFileName) //{ // context.Response.Clear(); // context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName); //HttpUtility.UrlEncode(fileName)); // context.Response.ContentType = "application/vnd.ms-excel"; // //HSSFWorkbook hssfworkbook = GenerateData(table, headerText, sheetName, columnName, columnTitle); // context.Response.BinaryWrite(ExportDT(dtSource, strHeaderText).GetBuffer()); // context.Response.End(); //} public static void Write(HttpContext context, DataTable dtSource, string strHeaderText, string strFileName) { context.Response.Clear(); context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName); //HttpUtility.UrlEncode(fileName)); context.Response.ContentType = "application/vnd.ms-excel"; HSSFWorkbook hssfworkbook = ExportDT(dtSource, strHeaderText); context.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer()); context.Response.End(); } public static bool isNumeric(String message, out double result) { Regex rex = new Regex(@"^[-]?\d+[.]?\d*$"); result = -1; if (rex.IsMatch(message)) { result = double.Parse(message); return true; } else return false; } } }
呼叫如下:
/// <summary> /// 匯出網銀 /// </summary> public void Excel() { //匯出table var MyDataTable = new DataTable(); MyDataTable.Columns.Add("id", Type.GetType("System.Int16")); MyDataTable.Columns.Add("hope_paydate", Type.GetType("System.String")); MyDataTable.Columns.Add("RemittanAcount", Type.GetType("System.String")); MyDataTable.Columns.Add("RemittanDempart", Type.GetType("System.String")); MyDataTable.Columns.Add("payee", Type.GetType("System.String")); MyDataTable.Columns.Add("CollectingBank", Type.GetType("System.String")); MyDataTable.Columns.Add("PaymentAccount", Type.GetType("System.String")); MyDataTable.Columns.Add("Account", Type.GetType("System.Double")); MyDataTable.Columns.Add("PaymentType", Type.GetType("System.String")); MyDataTable.Columns.Add("PaymentDate", Type.GetType("System.String")); MyDataTable.Columns.Add("PaymentYong", Type.GetType("System.String")); MyDataTable.Columns.Add("Mark", Type.GetType("System.String")); MyDataTable.Columns.Add("ReceivingProvinces", Type.GetType("System.String")); MyDataTable.Columns.Add("ReceivingShi", Type.GetType("System.String")); DataRow dr; for (int i = 0; i <= 9; i++) { dr = MyDataTable.NewRow(); dr["id"] = i+1; dr["hope_paydate"] = "222"; dr["RemittanAcount"] = "444"; dr["RemittanDempart"] = "555"; dr["payee"] = "666"; dr["CollectingBank"] = "666"; dr["PaymentAccount"] = "666"; dr["Account"] = "666"; dr["PaymentType"] = "666"; dr["PaymentDate"] = "666"; dr["PaymentYong"] = "666"; dr["Mark"] = "666"; dr["ReceivingProvinces"] = "666"; dr["ReceivingShi"] = "666"; MyDataTable.Rows.Add(dr); } var fileName = string.Format("網銀-{0}", DateTime.Now.ToString("yyyy-MM-dd")); string[] strFieldsName = { "序號","輸入日期","匯款帳號", "匯款部門", "收款人", "收款銀行","收款帳號","匯款金額","匯款型別" ,"匯款日期","匯款用途","備註", "收款省","收款市縣"}; string[] strFields = { "id", "hope_paydate", "RemittanAcount", "RemittanDempart", "payee", "CollectingBank", "PaymentAccount", "Account", "PaymentType", "PaymentDate", "PaymentYong","Mark","ReceivingProvinces","ReceivingShi"}; ExcelHelper.Write(HttpContext.Current, MyDataTable, fileName, fileName, strFields, strFieldsName, string.Format("{0}.xls", fileName)); }