NPOI 導出Execl 本身單獨工具類app
詳見代碼ide
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using System.Data; using System.IO; using System.Web; using System.Reflection; using System.ComponentModel; namespace NPOIHelper { public class NPOIHelper { /// <summary> /// DataTable導出到Excel文件 /// </summary> /// <param name="dt">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">保存位置</param> public static void ExportTableExecl(DataTable dt, string strHeaderText, string strFileName) { using (MemoryStream ms = Exprot(dt, strHeaderText)) { using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); } } } /// <summary> /// 用於Web 導出 /// </summary> /// <param name="dtSource">源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <param name="strFileName">文件名</param> public static void ExportByWeb(DataTable dtSource, string strHeaderText, string strFileName) { HttpContext context = HttpContext.Current; context.Response.ContentType = "application/vnd.ms-excel"; context.Response.ContentEncoding = Encoding.UTF8; context.Response.Charset = ""; context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8)); context.Response.BinaryWrite(Exprot(dtSource, strHeaderText).GetBuffer()); context.Response.End(); } /// <summary> /// 將泛型的list 集合導出Execl /// </summary> /// <typeparam name="T">實體對象</typeparam> /// <param name="list">集合</param> /// <param name="strHeaderText">表頭</param> /// <param name="strFileName">文件名字</param> public static void ExportToList<T>(List<T> list, string strHeaderText,string strFileName) { using (MemoryStream ms = ExprotToList<T>(list,strHeaderText)) { using (FileStream fs = new FileStream(strFileName,FileMode.Create,FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data,0,data.Length); fs.Flush(); } } } /// <summary> /// DataTable導出到Excel的MemoryStream /// </summary> /// <param name="dt">數據源DataTable</param> /// <param name="strHeaderText">表頭文本</param> /// <returns></returns> public static MemoryStream Exprot(DataTable dt, string strHeaderText) { HSSFWorkbook workBook = new HSSFWorkbook(); ISheet sheet = workBook.CreateSheet(); #region 右鍵屬性 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; workBook.DocumentSummaryInformation =dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "文件做者信息"; si.ApplicationName = "建立程序信息"; si.LastAuthor = "最後保存者信息"; si.Comments = "做者信息"; si.Title = "標題信息"; si.Subject = "主題信息"; si.CreateDateTime = DateTime.Now; workBook.SummaryInformation = si; } #endregion ICellStyle dateStyle = workBook.CreateCellStyle(); IDataFormat dateFormat = workBook.CreateDataFormat(); dateStyle.DataFormat = dateFormat.GetFormat("yyyy-MM-dd"); //獲取列寬 int[] arrCollWidth = new int[dt.Columns.Count]; foreach (DataColumn item in dt.Columns) { arrCollWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length; } for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < dt.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(dt.Rows[i][j].ToString()).Length; if (intTemp > arrCollWidth[j]) { arrCollWidth[j] = intTemp; } } } int rowIndex = 0; foreach (DataRow item in dt.Rows) { #region 新建表 填充表頭 列頭 樣式 { if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = workBook.CreateSheet(); } #region 表頭及樣式 { IRow headerRow = sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); //填充填表 ICellStyle headerStyle = workBook.CreateCellStyle(); headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = workBook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headerStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headerStyle; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dt.Columns.Count - 1)); // headerRow.Dispose(); } #endregion #region 列頭及樣式 { IRow headRow = sheet.CreateRow(1); ICellStyle headerStyle = workBook.CreateCellStyle(); headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = workBook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headerStyle.SetFont(font); foreach (DataColumn cl in dt.Columns) { headRow.CreateCell(cl.Ordinal).SetCellValue(cl.ColumnName); headRow.GetCell(cl.Ordinal).CellStyle = headerStyle; //設置列寬 sheet.SetColumnWidth(cl.Ordinal, (arrCollWidth[cl.Ordinal]+1)*256); } } #endregion rowIndex = 2; } } #endregion #region 填充內容 { IRow row = sheet.CreateRow(rowIndex); foreach (DataColumn column in dt.Columns) { ICell cell = row.CreateCell(column.Ordinal); string drValue = item[column].ToString(); switch (column.DataType.ToString()) { case "System.String": cell.SetCellValue(drValue); break; case "System.DateTime": DateTime dateV; DateTime.TryParse(drValue, out dateV); cell.SetCellValue(dateV); cell.CellStyle = dateStyle; break; case "System.Boolean": bool boolV; bool.TryParse(drValue, out boolV); cell.SetCellValue(boolV); break; case "System.Int16": case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); cell.SetCellValue(intV); break; case "System.Decimal": case "System.Double": double doubleV = 0; double.TryParse(drValue, out doubleV); cell.SetCellValue(doubleV); break; case "System.DBNull": cell.SetCellValue(""); break; default: cell.SetCellValue(""); break; } } } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workBook.Write(ms); ms.Flush(); ms.Position = 0; //sheet.Dispose(); //workBook.Dispose(); return ms; } } /// <summary> /// 將list 集合導處 Execl /// </summary> /// <param name="list">泛型集合</param> /// <param name="strHeaderName">表頭名字</param> /// <returns></returns> public static MemoryStream ExprotToList<T>(List<T> list, string strHeaderName) { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); //建立樣式 ICellStyle cellStyle = workbook.CreateCellStyle(); IDataFormat dataFormat = workbook.CreateDataFormat(); cellStyle.DataFormat = dataFormat.GetFormat("yyyy-MM-dd"); //IRow headerRow = sheet.CreateRow(0); //headerRow.CreateCell(0).SetCellValue(strHeaderName); //表頭樣式 IRow headerRow = sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderName); //填充填表 ICellStyle headerStyle = workbook.CreateCellStyle(); headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headerStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headerStyle; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, list[0].GetType().GetProperties().Length - 1)); IRow rows = sheet.CreateRow(1); //獲取list屬性值 PropertyInfo[] propertyInfo = list[0].GetType().GetProperties(); #region 獲取 實體 中的 [DisplayName("姓名")] { //獲取 實體 中的 [DisplayName("姓名")] Type entity = list[0].GetType(); for (int i = 0; i < propertyInfo.Length; i++) { var pName = entity.GetProperty(propertyInfo[i].Name.ToString()).GetCustomAttribute<DisplayNameAttribute>(); rows.CreateCell(i).SetCellValue(pName.DisplayName); } } #endregion #region 獲取實體的屬性值 { //for (int i = 0; i < propertyInfo.Length; i++) //{ // rows.CreateCell(i).SetCellValue(propertyInfo[i].Name.ToString()); //} } #endregion //填充內容 int propertyIndex = 2; foreach (var item in list) { IRow row = sheet.CreateRow(propertyIndex); for (int i = 0; i < propertyInfo.Length; i++) { var obj = propertyInfo[i].GetValue(item, null); row.CreateCell(i).SetCellValue(obj.ToString()); } propertyIndex++; } //寬度自適應 for (int i = 0; i < list.Count; i++) { sheet.AutoSizeColumn(i); } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } } /// <summary> /// 讀取Execl 表格 /// </summary> /// <param name="fileName">文件路徑</param> /// <returns></returns> public static DataTable GetReaderExecl(string fileName) { DataTable dt = new DataTable(); HSSFWorkbook workBook; using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { workBook = new HSSFWorkbook(fs); } ISheet sheet = workBook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow(0); int cellCount = headerRow.LastCellNum; for (int i = 0; i < cellCount; i++) { ICell cell = headerRow.GetCell(i); dt.Columns.Add(cell.ToString()); } for (int j = (sheet.FirstRowNum + 1); j <= sheet.LastRowNum; j++) { IRow row = sheet.GetRow(j); DataRow dr = dt.NewRow(); for (int i = row.FirstCellNum; i <= cellCount; i++) { if (row.GetCell(i) != null) { dr[i] = row.GetCell(i).ToString(); } } dt.Rows.Add(dr); } return dt; } } }
解析一下 泛型集合導出Execl 中的一個問題工具
第一步:首先定義一個實體類 this
public class People { [DisplayName("姓名")] public string name { get; set; } [DisplayName("年齡")] public string Age { get; set; } [DisplayName("性別")] public string Sex { get; set; } }
第二步:直接調用spa
NPOIHelper.NPOIHelper.ExportToList<People>(this.GetLists(), "list","list.xls");
這樣導出結果是這樣的3d
表頭顯示的是 中文的 也就是實體類中的DisplayName 的值;若是不想使用這個值,想使用屬性值得 也是能夠的;將上面的代碼 註釋一下,將下面的 的代碼解注一下 就OK 了excel
修改的代碼以下:code
/// <summary> /// 將list 集合導處 Execl /// </summary> /// <param name="list">泛型集合</param> /// <param name="strHeaderName">表頭名字</param> /// <returns></returns> public static MemoryStream ExprotToList<T>(List<T> list, string strHeaderName) { HSSFWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); //建立樣式 ICellStyle cellStyle = workbook.CreateCellStyle(); IDataFormat dataFormat = workbook.CreateDataFormat(); cellStyle.DataFormat = dataFormat.GetFormat("yyyy-MM-dd"); //IRow headerRow = sheet.CreateRow(0); //headerRow.CreateCell(0).SetCellValue(strHeaderName); //表頭樣式 IRow headerRow = sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderName); //填充填表 ICellStyle headerStyle = workbook.CreateCellStyle(); headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; IFont font = workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headerStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headerStyle; sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, list[0].GetType().GetProperties().Length - 1)); IRow rows = sheet.CreateRow(1); //獲取list屬性值 PropertyInfo[] propertyInfo = list[0].GetType().GetProperties(); #region 獲取 實體 中的 [DisplayName("姓名")] { //獲取 實體 中的 [DisplayName("姓名")] //Type entity = list[0].GetType(); //for (int i = 0; i < propertyInfo.Length; i++) //{ // var pName = entity.GetProperty(propertyInfo[i].Name.ToString()).GetCustomAttribute<DisplayNameAttribute>(); // rows.CreateCell(i).SetCellValue(pName.DisplayName); //} } #endregion #region 獲取實體的屬性值 { for (int i = 0; i < propertyInfo.Length; i++) { rows.CreateCell(i).SetCellValue(propertyInfo[i].Name.ToString()); } } #endregion //填充內容 int propertyIndex = 2; foreach (var item in list) { IRow row = sheet.CreateRow(propertyIndex); for (int i = 0; i < propertyInfo.Length; i++) { var obj = propertyInfo[i].GetValue(item, null); row.CreateCell(i).SetCellValue(obj.ToString()); } propertyIndex++; } //寬度自適應 for (int i = 0; i < list.Count; i++) { sheet.AutoSizeColumn(i); } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; } }
效果圖:orm