基於C#語言MVC框架NPOI控制元件匯出Excel表資料
阿新 • • 發佈:2019-01-01
控制元件bin檔案下載地址:https://download.csdn.net/download/u012949335/10610726 @{ ViewBag.Title = "dcxx"; } <script type="text/javascript" language="javascript"> function excelport() { var checktag=$("#ischecked:checked"); var form=$("<form action=\"dcxx\" method=\"post\"></form>"); $(document.body).append(form); form.submit(); } </script> <button type="button" class="but-primary" onclick="excelport()"> 匯出資料</button>
//呼叫方法 public ActionResult dcxx() { DataTable dt = dal.getlist(" 1=1 "); NpoiWorkbook book = new NpoiWorkbook(); book.CreateSheet(dt, "xxx資訊"); Stream excelstream = book.GetMemoryStream(); return File(excelstream, "application/octet-stream", "xx資訊.xls"); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NPOI.HSSF.UserModel; using NPOI.HPSF; using System.IO; using System.Data; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; namespace YidiTutor.Common.NOPI { /// <summary> /// 工作薄 /// </summary> public class NpoiWorkbook { public HSSFWorkbook workbook; public XSSFWorkbook workbook2007; public bool isExcel2007 = false;//生成excel2007 /// <summary> /// 表頭格式 /// </summary> private ICellStyle HeadStyle { get { if (!isExcel2007) { HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 11; font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold; font.FontName = "宋體"; headStyle.SetFont(font); return headStyle; } else { XSSFCellStyle headStyle = (XSSFCellStyle)workbook2007.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; XSSFFont font = (XSSFFont)workbook2007.CreateFont(); font.FontHeightInPoints = 11; font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold; font.FontName = "宋體"; headStyle.SetFont(font); return headStyle; } } } private ICellStyle HeadStyle_red { get { ICellStyle Iheadstyle = null; if (!isExcel2007) { HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 11; font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold; font.FontName = "宋體"; font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; headStyle.SetFont(font); Iheadstyle = headStyle; } else { XSSFCellStyle headStyle = (XSSFCellStyle)workbook2007.CreateCellStyle(); headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; headStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; XSSFFont font = (XSSFFont)workbook2007.CreateFont(); font.FontHeightInPoints = 11; font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.Bold; font.FontName = "宋體"; font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; headStyle.SetFont(font); Iheadstyle = headStyle; } return Iheadstyle; } } /// <summary> /// 時間格式 /// </summary> private ICellStyle DateStyle { get { ICellStyle datestyle = null; if (!isExcel2007) { HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); datestyle = dateStyle; } else { XSSFCellStyle dateStyle = (XSSFCellStyle)workbook2007.CreateCellStyle(); XSSFDataFormat format = (XSSFDataFormat)workbook2007.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); datestyle = dateStyle; } return datestyle; } } private ICellStyle ContentStyle { get { ICellStyle contentstyle = null; if (!isExcel2007) { HSSFCellStyle contentStyle = (HSSFCellStyle)workbook.CreateCellStyle(); contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 11; font.FontName = "宋體"; contentStyle.SetFont(font); contentstyle = contentStyle; } else { XSSFCellStyle contentStyle = (XSSFCellStyle)workbook2007.CreateCellStyle(); contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; XSSFFont font = (XSSFFont)workbook2007.CreateFont(); font.FontHeightInPoints = 11; font.FontName = "宋體"; contentStyle.SetFont(font); contentstyle = contentStyle; } return contentstyle; } } private ICellStyle ContentStyle_red { get { ICellStyle contentStyle_red = null; if (!isExcel2007) { HSSFCellStyle contentStyle = (HSSFCellStyle)workbook.CreateCellStyle(); contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 11; font.FontName = "宋體"; font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; contentStyle.SetFont(font); contentStyle_red = contentStyle; } else { XSSFCellStyle contentStyle = (XSSFCellStyle)workbook2007.CreateCellStyle(); contentStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; contentStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; XSSFFont font = (XSSFFont)workbook2007.CreateFont(); font.FontHeightInPoints = 11; font.FontName = "宋體"; font.Color = NPOI.HSSF.Util.HSSFColor.Red.Index; contentStyle.SetFont(font); contentStyle_red = contentStyle; } return contentStyle_red; } } /// <summary> /// 例項一個工作薄 /// </summary> public NpoiWorkbook() { workbook2007 = new XSSFWorkbook(); workbook = new HSSFWorkbook(); #region 右擊檔案 屬性資訊 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "SiBu"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.CreateDateTime = System.DateTime.Now; workbook.SummaryInformation = si; #endregion } /// <summary> /// 匯出excel初始化 /// </summary> /// <param name="isexcel2007"></param> public NpoiWorkbook(bool isexcel2007) : this() { isExcel2007 = isexcel2007; } /// <summary> /// 讀取excel初始化,載入Excel檔案 /// </summary> /// <param name="filePath">檔案路徑</param> public NpoiWorkbook(string filePath) { string filetype = Path.GetExtension(filePath).ToLower(); try { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (".xls".Equals(filetype)) { isExcel2007 = false; } else { isExcel2007 = true; } if (filetype.Equals(".xls")) { workbook = new HSSFWorkbook(file); isExcel2007 = false; } else { workbook2007 = new XSSFWorkbook(file); isExcel2007 = true; } } } catch (Exception ex) { } } /// <summary> /// 讀取excel初始化,載入Excel檔案流 /// </summary> /// <param name="excelstream">excel檔案流,使用場景:excel上傳匯入時候直接獲取的檔案流</param> /// <param name="filename">帶字尾名的檔名(格式如xx.xls或D:\excel\xx.xls)</param> public NpoiWorkbook(Stream excelstream, string filename) { string filetype = Path.GetExtension(filename).ToLower(); if (".xls".Equals(filetype)) { workbook = new HSSFWorkbook(excelstream); isExcel2007 = false; } else { workbook2007 = new XSSFWorkbook(excelstream); isExcel2007 = true; } } /// <summary> /// 獲取Sheet頁的資料 /// </summary> /// <param name="sheetIndex">Sheet頁Index,從0開始</param> /// <returns>DataTable</returns> public DataTable GetDataTable(int sheetIndex = 0) { DataTable dt = new DataTable(); ISheet sheet = null; IWorkbook iworkbook = null; if (!isExcel2007) { sheet = (HSSFSheet)workbook.GetSheetAt(sheetIndex); iworkbook = workbook; } else { sheet = (XSSFSheet)workbook2007.GetSheetAt(sheetIndex); iworkbook = workbook; } System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int j = 0; j < cellCount; j++) { ICell cell = headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { IRow row = sheet.GetRow(i); if (row == null) continue; DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { ICell cell = row.GetCell(j); if (cell != null) { if (cell.CellType == CellType.Numeric) { //NPOI中數字和日期都是NUMERIC型別的,這裡對其進行判斷是否是日期型別 if (HSSFDateUtil.IsCellDateFormatted(cell))//日期型別 { dataRow[j] = cell.DateCellValue; } else//其他數字型別 { dataRow[j] = cell.NumericCellValue; } } else if (cell.CellType == CellType.Blank)//空資料型別 { dataRow[j] = ""; } else if (cell.CellType == CellType.Formula)//公式型別 { HSSFFormulaEvaluator eva = new HSSFFormulaEvaluator(iworkbook); dataRow[j] = eva.Evaluate(cell).StringValue; } else //其他型別都按字串型別來處理 { dataRow[j] = cell.StringCellValue; } } } dt.Rows.Add(dataRow); } return dt; } /// <summary> /// 建立一個Sheet頁 /// </summary> /// <param name="Sheet">Sheet</param> public void CreateSheet(Sheet sheetInfo) { if (string.IsNullOrWhiteSpace(sheetInfo.Name)) sheetInfo.Name = "Sheet" + workbook.NumberOfSheets + 1; HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(sheetInfo.Name); int rowIndex = 0; #region 新建表,填充表頭,填充列頭,樣式 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(rowIndex); headerRow.HeightInPoints = 20; var columIndex = 0; foreach (var column in sheetInfo.Columns) { headerRow.CreateCell(columIndex).SetCellValue(column.Name); if ("Red".Equals(column.ColorType)) headerRow.GetCell(columIndex).CellStyle = HeadStyle_red; else headerRow.GetCell(columIndex).CellStyle = HeadStyle; //設定列寬 sheet.SetColumnWidth(columIndex, column.Width * 256); sheet.SetColumnHidden(columIndex, column.Hidden); columIndex++; } #endregion #region 填充內容 rowIndex = 1; HSSFCellStyle contentStyle = (HSSFCellStyle)ContentStyle; foreach (DataRow row in sheetInfo.DataSource.Rows) { HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); var columnIndex = 0; //dataRow.RowStyle = ContentStyle; foreach (var column in sheetInfo.Columns) { HSSFCell newCell = (HSSFCell)dataRow.CreateCell(columnIndex); if (!sheetInfo.DataSource.Columns.Contains(column.Code)) { newCell.SetCellValue(""); } else { string drValue = row[column.Code].ToString(); switch (column.DataType.ToUpper()) { case "S"://字串型別 newCell.SetCellValue(drValue); if ("Red".Equals(column.ColorType)) newCell.CellStyle = ContentStyle_red;//格式化顯示 else newCell.CellStyle = contentStyle;//格式化顯示 break; case "D"://日期型別 System.DateTime dateV; System.DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = contentStyle;//格式化顯示 break; case "B"://布林型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "I"://整型 int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "F"://浮點型 double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; default: newCell.SetCellValue(drValue); break; } } columnIndex++; } rowIndex++; } #endregion } public void CreateSheet(DataTable dt, string sheetname) { Sheet sheet = new Sheet(); sheet.Name = sheetname; List<Column> columns = new List<Column>(); for (int i = 0; i < dt.Columns.Count; i++) { DataColumn col = dt.Columns[i]; Column column = new Column(); column.Code = col.ColumnName; column.Name = col.ColumnName; column.DataType = "S"; column.Width = 30; column.Hidden = false; columns.Add(column); } sheet.Columns = columns; sheet.DataSource = dt; if (!isExcel2007) { this.CreateSheet(sheet); } else { this.CreateSheet2007(sheet); } } public void CreateSheet2007(Sheet sheetInfo) { if (string.IsNullOrWhiteSpace(sheetInfo.Name)) sheetInfo.Name = "Sheet" + workbook2007.NumberOfSheets + 1; XSSFSheet sheet = (XSSFSheet)workbook2007.CreateSheet(sheetInfo.Name); int rowIndex = 0; #region 新建表,填充表頭,填充列頭,樣式 XSSFRow headerRow = (XSSFRow)sheet.CreateRow(rowIndex); headerRow.HeightInPoints = 20; var columIndex = 0; foreach (var column in sheetInfo.Columns) { headerRow.CreateCell(columIndex).SetCellValue(column.Name); if ("Red".Equals(column.ColorType)) headerRow.GetCell(columIndex).CellStyle = HeadStyle_red; else headerRow.GetCell(columIndex).CellStyle = HeadStyle; //設定列寬 sheet.SetColumnWidth(columIndex, column.Width * 256); sheet.SetColumnHidden(columIndex, column.Hidden); columIndex++; } #endregion #region 填充內容 rowIndex = 1; XSSFCellStyle contentStyle = (XSSFCellStyle)ContentStyle; //XSSF contentStyle = (HSSFCellStyle)ContentStyle; foreach (DataRow row in sheetInfo.DataSource.Rows) { XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex); var columnIndex = 0; //dataRow.RowStyle = ContentStyle; foreach (var column in sheetInfo.Columns) { XSSFCell newCell = (XSSFCell)dataRow.CreateCell(columnIndex); if (!sheetInfo.DataSource.Columns.Contains(column.Code)) { newCell.SetCellValue(""); } else { string drValue = row[column.Code].ToString(); switch (column.DataType.ToUpper()) { case "S"://字串型別 newCell.SetCellValue(drValue); if ("Red".Equals(column.ColorType)) newCell.CellStyle = ContentStyle_red;//格式化顯示 else newCell.CellStyle = contentStyle;//格式化顯示 break; case "D"://日期型別 System.DateTime dateV; System.DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = contentStyle;//格式化顯示 break; case "B"://布林型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "I"://整型 int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "F"://浮點型 double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; default: newCell.SetCellValue(drValue); break; } } columnIndex++; } rowIndex++; } #endregion } /// <summary> /// 儲存 /// </summary> /// <param name="filePath">檔案路徑</param> public void SaveAs(string filePath) { using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// 獲取Workbook的MemoryStream /// </summary> /// <returns></returns> public MemoryStream GetMemoryStream() { MemoryStream ms = new MemoryStream(); if (!isExcel2007) { workbook.Write(ms); ms.Flush(); ms.Position = 0; } else { workbook2007.Write(ms); } return ms; } } public class Column { public string Code { get; set; } public string Name { get; set; } public string DataType { get; set; } public int Width { get; set; } public bool Hidden { get; set; } public string ColorType { get; set; } public Column() { } public Column(string code, string name, string dataType, int width, bool hidden = false) { Code = code; Name = name; DataType = dataType; Width = width; Hidden = hidden; } } public class Sheet { public string Name { get; set; } public List<Column> Columns { get; set; } public DataTable DataSource { get; set; } public Sheet() { } public Sheet(string name, List<Column> columns, DataTable dataSource) { Name = name; Columns = columns; DataSource = dataSource; } } }