1. 程式人生 > >NPOI幫助類

NPOI幫助類

bre lencod live bool ntc class enc att 定義

/// <summary>
    /// NPOI導出幫助類
    /// </summary>
    public class NPOIHelper
    {
        /// <summary>
        /// DataTable導出到Excel的MemoryStream
        /// </summary>
        /// <param name="dt">源DataTable</param>
        /// <param name="dicTableHeader">表頭文本</param>
        private
static MemoryStream Export(DataTable dt, Dictionary<string, string> dicTableHeader) { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("工作表1"); IRow headerRow = sheet.CreateRow(0); int headerIndex = 0; ICellStyle headerCellStyle
= Getcellstyle(workbook, stylexls.頭); ICellStyle dateCellStyle = Getcellstyle(workbook, stylexls.時間); foreach (var item in dicTableHeader) { ICell cell = headerRow.CreateCell(headerIndex); cell.CellStyle = headerCellStyle; cell.SetCellValue(item.Value); headerIndex
= headerIndex + 1; } sheet.CreateFreezePane(0, 1, 0, 1); int rowCount = dt.Rows.Count; for (int i = 0; i < rowCount; i++) { IRow row = sheet.CreateRow(i + 1); int rowIndex = 0; foreach (var item in dicTableHeader) { ICell newCell = row.CreateCell(rowIndex); rowIndex = rowIndex + 1; DataColumn dc = dt.Columns[item.Key]; string drValue = dt.Rows[i][item.Key].ToString(); switch (dc.DataType.ToString()) { case "System.String"://字符串類型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期類型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateCellStyle;//格式化顯示 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(""); break; } } } ////自動列寬 //for (int i = 0; i <= dicTableHeader.Count; i++) // sheet.AutoSizeColumn(i, true); using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } } /// <summary> /// DataTable導出到Excel的MemoryStream /// </summary> /// <param name="dt">數據源DataTable</param> /// <param name="heardList">頭部列表</param> /// <returns></returns> private static MemoryStream Export(DataTable dt, IList<SYS_DICT> heardList) { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet("工作表1"); ICellStyle headerCellStyle = Getcellstyle(workbook, stylexls.頭); ICellStyle dateCellStyle = Getcellstyle(workbook, stylexls.時間); IRow headerRow = sheet.CreateRow(0); int headerIndex = 0; foreach (var item in heardList) { ICell cell = headerRow.CreateCell(headerIndex); cell.CellStyle = headerCellStyle; cell.SetCellValue(item.fname_ch); headerIndex = headerIndex + 1; } sheet.CreateFreezePane(0, 1, 0, 1); int rowCount = dt.Rows.Count; for (int i = 0; i < rowCount; i++) { IRow row = sheet.CreateRow(i + 1); int rowIndex = 0; foreach (var item in heardList) { ICell newCell = row.CreateCell(rowIndex); rowIndex = rowIndex + 1; DataColumn dc = dt.Columns[item.field_name]; string drValue = dt.Rows[i][item.field_name].ToString(); switch (dc.DataType.ToString()) { case "System.String"://字符串類型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期類型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateCellStyle;//格式化顯示 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(""); break; } } } ////自動列寬 //for (int i = 0; i <= dicTableHeader.Count; i++) // sheet.AutoSizeColumn(i, true); int heardListLen = heardList.Count; for (int i = 0; i < heardListLen; i++) { int width = 0; int.TryParse(heardList[i].ExcelColWidth.ToString(), out width); width = (int)((width + 0.72) * 256); sheet.SetColumnWidth(i, width); } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } } /// <summary> /// 用於Web導出 /// </summary> /// <param name="dt">數據源DataTable</param> /// <param name="strFileName">文件名</param> /// <param name="dicTableHeader">導出對照</param> public static void ExportByWeb(DataTable dt, string strFileName, Dictionary<string, string> dicTableHeader) { HttpContext curContext = HttpContext.Current; // 設置編碼和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; strFileName = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss"); string fileName = HttpUtility.UrlEncode(strFileName, Encoding.UTF8) + ".xls"; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); curContext.Response.BinaryWrite(Export(dt, dicTableHeader).GetBuffer()); curContext.Response.End(); } /// <summary> /// Web Excel導出 /// </summary> /// <param name="dt">數據源DataTable</param> /// <param name="strFileName">文件名</param> /// <param name="heardList">頭部列表</param> public static void ExportByWeb(DataTable dt, string strFileName, IList<SYS_DICT> heardList) { HttpContext curContext = HttpContext.Current; // 設置編碼和附件格式 curContext.Response.ContentType = "application/vnd.ms-excel"; curContext.Response.ContentEncoding = Encoding.UTF8; curContext.Response.Charset = ""; strFileName = strFileName + DateTime.Now.ToString("yyyyMMddHHmmss"); string fileName = HttpUtility.UrlEncode(strFileName, Encoding.UTF8) + ".xls"; curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); curContext.Response.BinaryWrite(Export(dt, heardList).GetBuffer()); curContext.Response.End(); } #region 定義單元格常用到樣式的枚舉 public enum stylexls { 頭, url, 時間, 數字, 錢, 百分比, 中文大寫, 科學計數法, 默認 } #endregion #region 定義單元格常用到樣式 private static ICellStyle Getcellstyle(IWorkbook wb, stylexls str) { ICellStyle cellStyle = wb.CreateCellStyle(); //定義幾種字體 //也可以一種字體,寫一些公共屬性,然後在下面需要時加特殊的 IFont font12 = wb.CreateFont(); font12.FontHeightInPoints = 10; font12.FontName = "微軟雅黑"; IFont headerFont = wb.CreateFont(); headerFont.FontHeightInPoints = 10; headerFont.IsBold = true; headerFont.FontName = "微軟雅黑"; IFont font = wb.CreateFont(); font.FontName = "微軟雅黑"; //font.Underline = 1;下劃線 IFont fontcolorblue = wb.CreateFont(); fontcolorblue.Color = HSSFColor.OliveGreen.Blue.Index; fontcolorblue.IsItalic = true;//下劃線 fontcolorblue.FontName = "微軟雅黑"; //邊框 cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Dotted; cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Hair; cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Hair; cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Dotted; //邊框顏色 cellStyle.BottomBorderColor = HSSFColor.OliveGreen.Blue.Index; cellStyle.TopBorderColor = HSSFColor.OliveGreen.Blue.Index; //背景圖形,我沒有用到過。感覺很醜 //cellStyle.FillBackgroundColor = HSSFColor.OLIVE_GREEN.BLUE.index; //cellStyle.FillForegroundColor = HSSFColor.OLIVE_GREEN.BLUE.index; cellStyle.FillForegroundColor = HSSFColor.White.Index; // cellStyle.FillPattern = FillPatternType.NO_FILL; cellStyle.FillBackgroundColor = HSSFColor.Blue.Index; //水平對齊 cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; //垂直對齊 cellStyle.VerticalAlignment = VerticalAlignment.Center; //自動換行 cellStyle.WrapText = true; //縮進;當設置為1時,前面留的空白太大了。希旺官網改進。或者是我設置的不對 cellStyle.Indention = 0; //上面基本都是設共公的設置 //下面列出了常用的字段類型 switch (str) { case stylexls.頭: cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; // cellStyle.FillPattern = FillPatternType.LEAST_DOTS; cellStyle.SetFont(headerFont); break; case stylexls.時間: IDataFormat datastyle = wb.CreateDataFormat(); cellStyle.DataFormat = datastyle.GetFormat("yyyy-MM-dd HH:mm:ss"); cellStyle.SetFont(font); break; case stylexls.數字: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00"); cellStyle.SetFont(font); break; case stylexls.錢: IDataFormat format = wb.CreateDataFormat(); cellStyle.DataFormat = format.GetFormat("¥#,##0"); cellStyle.SetFont(font); break; case stylexls.url: fontcolorblue.Underline = FontUnderlineType.Single; cellStyle.SetFont(fontcolorblue); break; case stylexls.百分比: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00%"); cellStyle.SetFont(font); break; case stylexls.中文大寫: IDataFormat format1 = wb.CreateDataFormat(); cellStyle.DataFormat = format1.GetFormat("[DbNum2][$-804]0"); cellStyle.SetFont(font); break; case stylexls.科學計數法: cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("0.00E+00"); cellStyle.SetFont(font); break; case stylexls.默認: cellStyle.SetFont(font); break; } return cellStyle; } #endregion }

NPOI幫助類