使用NPOI导出Excel模板
生活随笔
收集整理的這篇文章主要介紹了
使用NPOI导出Excel模板
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
導出Excel包含的功能:
1.多表頭導出最多支持到三行,表頭格式說明
相鄰父列頭之間用’#’分隔,父列頭與子列頭用空格(’ ‘)分隔,相鄰子列頭用逗號分隔(‘,’)
兩行:序號#分公司#組別#本日成功簽約單數 預警,續約,流失,合計#累計成功簽約單數 預警,續約,流失,合計#任務數#完成比例#排名
三行:等級#級別#上期結存 件數,重量,比例#本期調入 收購調入 件數,重量,比例#本期發出 車間投料 件數,重量,比例#本期發出 產品外銷百分比 件數,重量,比例#平均值
三行時請注意:列頭要重復
2.添加表頭標題功能
3.添加序號功能
4.根據數據設置列寬
實體類
NPOIModel.cs
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web;namespace NPOIDemo.Model {/// <summary>/// 實體類/// </summary>public class NPOIModel{/// <summary>/// 數據源/// </summary>public DataTable dataSource { get; private set; }/// <summary>/// 要導出的數據列數組/// </summary>public string[] fileds { get; private set; }/// <summary>/// 工作薄名稱數組/// </summary>public string sheetName { get; private set; }/// <summary>/// 表標題/// </summary>public string tableTitle { get; private set; }/// <summary>/// 表標題是否存在 1:存在 0:不存在/// </summary>public int isTitle { get; private set; }/// <summary>/// 是否添加序號/// </summary>public int isOrderby { get; private set; }/// <summary>/// 表頭/// </summary>public string headerName { get; private set; }/// <summary>/// 取得列寬/// </summary>public int[] colWidths { get; private set; }/// <summary>/// 構造函數/// </summary>/// <param name="dataSource">數據來源 DataTable</param>/// <param name="filed">要導出的字段,如果為空或NULL,則默認全部</param> /// <param name="sheetName">工作薄名稱</param>/// <param name="headerName">表頭名稱 如果為空或NULL,則默認數據列字段/// 相鄰父列頭之間用'#'分隔,父列頭與子列頭用空格(' ')分隔,相鄰子列頭用逗號分隔(',')/// 兩行:序號#分公司#組別#本日成功簽約單數 預警,續約,流失,合計#累計成功簽約單數 預警,續約,流失,合計#任務數#完成比例#排名 /// 三行:等級#級別#上期結存 件數,重量,比例#本期調入 收購調入 件數,重量,比例#本期發出 車間投料 件數,重量,比例#本期發出 產品外銷百分比 件數,重量,比例#平均值 /// 三行時請注意:列頭要重復/// </param>/// <param name="tableTitle">表標題</param> /// <param name="isOrderby">是否添加序號 0:不添加 1:添加</param>public NPOIModel(DataTable dataSource, string filed, string sheetName, string headerName, string tableTitle = null, int isOrderby = 0){if (!string.IsNullOrEmpty(filed)){this.fileds = filed.ToUpper().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);// 移除多余數據列for (int i = dataSource.Columns.Count - 1; i >= 0; i--){DataColumn dc = dataSource.Columns[i];if (!this.fileds.Contains(dataSource.Columns[i].Caption.ToUpper())){dataSource.Columns.Remove(dataSource.Columns[i]);}}// 列索引int colIndex = 0;// 循環排序for (int i = 0; i < dataSource.Columns.Count; i++){// 獲取索引colIndex = GetColIndex(dataSource.Columns[i].Caption.ToUpper());// 設置下標dataSource.Columns[i].SetOrdinal(colIndex);}}else{this.fileds = new string[dataSource.Columns.Count];for (int i = 0; i < dataSource.Columns.Count; i++){this.fileds[i] = dataSource.Columns[i].ColumnName;}}this.dataSource = dataSource;if (!string.IsNullOrEmpty(sheetName))this.sheetName = sheetName;if (!string.IsNullOrEmpty(headerName))this.headerName = headerName;elsethis.headerName = string.Join("#", this.fileds);if (!string.IsNullOrEmpty(tableTitle)){this.tableTitle = tableTitle;this.isTitle = 1;}// 取得數據列寬 數據列寬可以和表頭列寬比較,采取最長寬度 colWidths = new int[this.dataSource.Columns.Count];foreach (DataColumn item in this.dataSource.Columns)colWidths[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;// 循環比較最大寬度for (int i = 0; i < this.dataSource.Rows.Count; i++){for (int j = 0; j < this.dataSource.Columns.Count; j++){int intTemp = Encoding.GetEncoding(936).GetBytes(this.dataSource.Rows[i][j].ToString()).Length;if (intTemp > colWidths[j])colWidths[j] = intTemp;}}if (isOrderby > 0){this.isOrderby = isOrderby;this.headerName = "序號#" + this.headerName;}}/// <summary>/// 獲取列名下標/// </summary>/// <param name="colName">列名稱</param>/// <returns></returns>private int GetColIndex(string colName){for (int i = 0; i < this.fileds.Length; i++){if (colName == this.fileds[i])return i;}return 0;}} }NPOIHeader.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web;namespace NPOIDemo.Model {/// <summary>/// 表頭構建類/// </summary>public class NPOIHeader{/// <summary>/// 表頭/// </summary>public string headerName { get; set; }/// <summary>/// 起始行/// </summary>public int firstRow { get; set; }/// <summary>/// 結束行/// </summary>public int lastRow { get; set; }/// <summary>/// 起始列/// </summary>public int firstCol { get; set; }/// <summary>/// 結束列/// </summary>public int lastCol { get; set; }/// <summary>/// 是否跨行/// </summary>public int isRowSpan { get; private set; }/// <summary>/// 是否跨列/// </summary>public int isColSpan { get; private set; }/// <summary>/// 外加行/// </summary>public int rows { get; set; }public NPOIHeader() { }/// <summary>/// 構造函數/// </summary>/// <param name="headerName">表頭</param>/// <param name="firstRow">起始行</param>/// <param name="lastRow">結束行</param>/// <param name="firstCol">起始列</param>/// <param name="lastCol">結束列</param>/// <param name="rows">外加行</param>/// <param name="cols">外加列</param>public NPOIHeader(string headerName, int firstRow, int lastRow, int firstCol, int lastCol, int rows = 0){this.headerName = headerName;this.firstRow = firstRow;this.lastRow = lastRow;this.firstCol = firstCol;this.lastCol = lastCol;// 是否跨行判斷if (firstRow != lastRow)isRowSpan = 1;if (firstCol != lastCol)isColSpan = 1;this.rows = rows;}} }NPOIHelper.cs輔助類
using System; using System.Linq; using System.Web; using System.IO; using NPOI; using NPOI.SS.Util; using NPOI.HSSF.Util; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using System.Data; using System.Collections.Generic; using System.Text; using NPOIDemo.Model;namespace NPOIDemo {/// <summary>/// Excel導出/// </summary>public class NPOIHelper{#region 初始化/// <summary>/// 聲明 HSSFWorkbook 對象/// </summary>private static HSSFWorkbook _workbook;/// <summary>/// 聲明 HSSFSheet 對象/// </summary>private static HSSFSheet _sheet;#endregion/// <summary>/// Excel導出/// </summary>/// <param name="fileName">文件名稱 如果為空或NULL,則默認“新建Excel.xls”</param>/// <param name="list"></param>/// <param name="method">導出方式 1:WEB導出(默認)2:按文件路徑導出</param>/// <param name="filePath">文件路徑 如果WEB導出,則可以為空;如果按文件路徑導出,則默認桌面路徑</param>public static void Export(string fileName, IList<NPOIModel> list, int method = 1, string filePath = null){// 文件名稱if (!string.IsNullOrEmpty(fileName)){if (fileName.IndexOf('.') == -1)fileName += ".xls";elsefileName = fileName.Substring(1, fileName.IndexOf('.')) + ".xls";}elsefileName = "新建Excel.xls";// 文件路徑if (2 == method && string.IsNullOrEmpty(filePath))filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);// 調用導出處理程序Export(list);// WEB導出if (1 == method){System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";//設置下載的Excel文件名System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));using (MemoryStream ms = new MemoryStream()){//將工作簿的內容放到內存流中_workbook.Write(ms);//將內存流轉換成字節數組發送到客戶端System.Web.HttpContext.Current.Response.BinaryWrite(ms.GetBuffer());System.Web.HttpContext.Current.Response.End();_sheet = null;_workbook = null;}}else if (2 == method){using (FileStream fs = File.Open(filePath, FileMode.Append)){_workbook.Write(fs);_sheet = null;_workbook = null;}}}/// <summary>/// 導出方法實現/// </summary>/// <param name="list"></param>private static void Export(IList<NPOIModel> list){#region 變量聲明// 初始化_workbook = new HSSFWorkbook();// 聲明 Row 對象IRow _row;// 聲明 Cell 對象ICell _cell;// 總列數int cols = 0;// 總行數int rows = 0;// 行數計數器int rowIndex = 0;// 單元格值string drValue = null;#endregionforeach (NPOIModel model in list){// 工作薄命名if (model.sheetName != null)_sheet = (HSSFSheet)_workbook.CreateSheet(model.sheetName);else_sheet = (HSSFSheet)_workbook.CreateSheet();// 獲取數據源DataTable dt = model.dataSource;// 初始化rowIndex = 0;// 獲取總行數rows = GetRowCount(model.headerName);// 獲取總列數cols = GetColCount(model.headerName);// 循環行數foreach (DataRow row in dt.Rows){#region 新建表,填充表頭,填充列頭,樣式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0)_sheet = (HSSFSheet)_workbook.CreateSheet();// 構建行for (int i = 0; i < rows + model.isTitle; i++){_row = _sheet.GetRow(i);// 創建行if (_row == null)_row = _sheet.CreateRow(i);for (int j = 0; j < cols; j++)_row.CreateCell(j).CellStyle = bodyStyle;}// 如果存在表標題if (model.isTitle > 0){// 獲取行_row = _sheet.GetRow(0);// 合并單元格CellRangeAddress region = new CellRangeAddress(0, 0, 0, (cols - 1));_sheet.AddMergedRegion(region);// 填充值_row.CreateCell(0).SetCellValue(model.tableTitle);// 設置樣式_row.GetCell(0).CellStyle = titleStyle;// 設置行高_row.HeightInPoints = 20;}// 取得上一個實體NPOIHeader lastRow = null;IList<NPOIHeader> hList = GetHeaders(model.headerName, rows, model.isTitle);// 創建表頭foreach (NPOIHeader m in hList){var data = hList.Where(c => c.firstRow == m.firstRow && c.lastCol == m.firstCol - 1);if (data.Count() > 0){lastRow = data.First();if (m.headerName == lastRow.headerName)m.firstCol = lastRow.firstCol;}// 獲取行_row = _sheet.GetRow(m.firstRow);// 合并單元格CellRangeAddress region = new CellRangeAddress(m.firstRow, m.lastRow, m.firstCol, m.lastCol);_sheet.AddMergedRegion(region);// 填充值_row.CreateCell(m.firstCol).SetCellValue(m.headerName);}// 填充表頭樣式for (int i = 0; i < rows + model.isTitle; i++){_row = _sheet.GetRow(i);for (int j = 0; j < cols; j++){_row.GetCell(j).CellStyle = bodyStyle;//設置列寬_sheet.SetColumnWidth(j, (model.colWidths[j] + 1) * 256);}}rowIndex = (rows + model.isTitle);}#endregion#region 填充內容// 構建列_row = _sheet.CreateRow(rowIndex);foreach (DataColumn column in dt.Columns){// 添加序號列if (1 == model.isOrderby && column.Ordinal == 0){_cell = _row.CreateCell(0);_cell.SetCellValue(rowIndex - rows);_cell.CellStyle = bodyStyle;}// 創建列_cell = _row.CreateCell(column.Ordinal + model.isOrderby);// 獲取值drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串類型_cell.SetCellValue(drValue);_cell.CellStyle = bodyStyle;break;case "System.DateTime"://日期類型DateTime dateV;DateTime.TryParse(drValue, out dateV);_cell.SetCellValue(dateV);_cell.CellStyle = dateStyle;//格式化顯示break;case "System.Boolean"://布爾型bool boolV = false;bool.TryParse(drValue, out boolV);_cell.SetCellValue(boolV);_cell.CellStyle = bodyStyle;break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV);_cell.SetCellValue(intV);_cell.CellStyle = bodyRightStyle;break;case "System.Decimal"://浮點型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV);_cell.SetCellValue(doubV);_cell.CellStyle = bodyRightStyle;break;case "System.DBNull"://空值處理_cell.SetCellValue("");break;default:_cell.SetCellValue("");break;}}#endregionrowIndex++;}}}#region 輔助方法/// <summary>/// 表頭解析/// </summary>/// <remarks>/// author:zhujt/// create date:2015-9-10 19:24:51/// </remarks>/// <param name="header">表頭</param>/// <param name="rows">總行數</param>/// <param name="addRows">外加行</param>/// <param name="addCols">外加列</param>/// <returns></returns>private static IList<NPOIHeader> GetHeaders(string header, int rows, int addRows){// 臨時表頭數組string[] tempHeader;string[] tempHeader2;// 所跨列數int colSpan = 0;// 所跨行數int rowSpan = 0;// 單元格對象NPOIHeader model = null;// 行數計數器int rowIndex = 0;// 列數計數器int colIndex = 0;// IList<NPOIHeader> list = new List<NPOIHeader>();// 初步解析string[] headers = header.Split(new string[] { "#" }, StringSplitOptions.RemoveEmptyEntries);// 表頭遍歷for (int i = 0; i < headers.Length; i++){// 行數計數器清零rowIndex = 0;// 列數計數器清零colIndex = 0;// 獲取所跨行數rowSpan = GetRowSpan(headers[i], rows);// 獲取所跨列數colSpan = GetColSpan(headers[i]);// 如果所跨行數與總行數相等,則不考慮是否合并單元格問題if (rows == rowSpan){colIndex = GetMaxCol(list);model = new NPOIHeader(headers[i],addRows,(rowSpan - 1 + addRows),colIndex,(colSpan - 1 + colIndex),addRows);list.Add(model);rowIndex += (rowSpan - 1) + addRows;}else{// 列索引colIndex = GetMaxCol(list);// 如果所跨行數不相等,則考慮是否包含多行tempHeader = headers[i].Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);for (int j = 0; j < tempHeader.Length; j++){// 如果總行數=數組長度if (1 == GetColSpan(tempHeader[j])){if (j == tempHeader.Length - 1 && tempHeader.Length < rows){model = new NPOIHeader(tempHeader[j],(j + addRows),(j + addRows) + (rows - tempHeader.Length),colIndex,(colIndex + colSpan - 1),addRows);list.Add(model);}else{model = new NPOIHeader(tempHeader[j],(j + addRows),(j + addRows),colIndex,(colIndex + colSpan - 1),addRows);list.Add(model);}}else{// 如果所跨列數不相等,則考慮是否包含多列tempHeader2 = tempHeader[j].Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);for (int m = 0; m < tempHeader2.Length; m++){// 列索引colIndex = GetMaxCol(list) - colSpan + m;if (j == tempHeader.Length - 1 && tempHeader.Length < rows){model = new NPOIHeader(tempHeader2[m],(j + addRows),(j + addRows) + (rows - tempHeader.Length),colIndex,colIndex,addRows);list.Add(model);}else{model = new NPOIHeader(tempHeader2[m],(j + addRows),(j + addRows),colIndex,colIndex,addRows);list.Add(model);}}}rowIndex += j + addRows;}}}return list;}/// <summary>/// 獲取最大列/// </summary>/// <param name="list"></param>/// <returns></returns>private static int GetMaxCol(IList<NPOIHeader> list){int maxCol = 0;if (list.Count > 0){foreach (NPOIHeader model in list){if (maxCol < model.lastCol)maxCol = model.lastCol;}maxCol += 1;}return maxCol;}/// <summary>/// 獲取表頭行數/// </summary>/// <param name="newHeaders">表頭文字</param>/// <returns></returns>private static int GetRowCount(string newHeaders){string[] ColumnNames = newHeaders.Split(new char[] { '@' });int Count = 0;if (ColumnNames.Length <= 1)ColumnNames = newHeaders.Split(new char[] { '#' });foreach (string name in ColumnNames){int TempCount = name.Split(new char[] { ' ' }).Length;if (TempCount > Count)Count = TempCount;}return Count;}/// <summary>/// 獲取表頭列數/// </summary>/// <param name="newHeaders">表頭文字</param>/// <returns></returns>private static int GetColCount(string newHeaders){string[] ColumnNames = newHeaders.Split(new char[] { '@' });int Count = 0;if (ColumnNames.Length <= 1)ColumnNames = newHeaders.Split(new char[] { '#' });Count = ColumnNames.Length;foreach (string name in ColumnNames){int TempCount = name.Split(new char[] { ',' }).Length;if (TempCount > 1)Count += TempCount - 1;}return Count;}/// <summary>/// 列頭跨列數/// </summary>/// <remarks>/// author:zhujt/// create date:2015-9-9 09:17:34/// </remarks>/// <param name="newHeaders">表頭文字</param>/// <returns></returns>private static int GetColSpan(string newHeaders){return newHeaders.Split(',').Count();}/// <summary>/// 列頭跨行數/// </summary> /// <remarks>/// author:zhujt/// create date:2015-9-9 09:17:14/// </remarks>/// <param name="newHeaders">列頭文本</param>/// <param name="rows">表頭總行數</param>/// <returns></returns>private static int GetRowSpan(string newHeaders, int rows){int Count = newHeaders.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).Length;// 如果總行數與當前表頭所擁有行數相等if (rows == Count)Count = 1;else if (Count < rows)Count = 1 + (rows - Count);elsethrow new Exception("表頭格式不正確!");return Count;}#endregion#region 單元格樣式/// <summary>/// 數據單元格樣式/// </summary>private static ICellStyle bodyStyle{get{ICellStyle style = _workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.Center; //居中style.VerticalAlignment = VerticalAlignment.Center;//垂直居中 style.WrapText = true;//自動換行// 邊框style.BorderBottom = BorderStyle.Thin;style.BorderLeft = BorderStyle.Thin;style.BorderRight = BorderStyle.Thin;style.BorderTop = BorderStyle.Thin;// 字體IFont font = _workbook.CreateFont();font.FontHeightInPoints = 10;font.FontName = "宋體";style.SetFont(font);return style;}}/// <summary>/// 數據單元格樣式/// </summary>private static ICellStyle bodyRightStyle{get{ICellStyle style = _workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.Right; //居中style.VerticalAlignment = VerticalAlignment.Center;//垂直居中 style.WrapText = true;//自動換行// 邊框style.BorderBottom = BorderStyle.Thin;style.BorderLeft = BorderStyle.Thin;style.BorderRight = BorderStyle.Thin;style.BorderTop = BorderStyle.Thin;// 字體IFont font = _workbook.CreateFont();font.FontHeightInPoints = 10;font.FontName = "宋體";style.SetFont(font);return style;}}/// <summary>/// 標題單元格樣式/// </summary>private static ICellStyle titleStyle{get{ICellStyle style = _workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.Center; //居中style.VerticalAlignment = VerticalAlignment.Center;//垂直居中 style.WrapText = true;//自動換行 IFont font = _workbook.CreateFont();font.FontHeightInPoints = 14;font.FontName = "宋體";font.Boldweight = (short)FontBoldWeight.Bold;style.SetFont(font);return style;}}/// <summary>/// 日期單元格樣式/// </summary>private static ICellStyle dateStyle{get{ICellStyle style = _workbook.CreateCellStyle();style.Alignment = HorizontalAlignment.Center; //居中style.VerticalAlignment = VerticalAlignment.Center;//垂直居中 style.WrapText = true;//自動換行// 邊框style.BorderBottom = BorderStyle.Thin;style.BorderLeft = BorderStyle.Thin;style.BorderRight = BorderStyle.Thin;style.BorderTop = BorderStyle.Thin;// 字體IFont font = _workbook.CreateFont();font.FontHeightInPoints = 10;font.FontName = "宋體";style.SetFont(font);IDataFormat format = _workbook.CreateDataFormat();style.DataFormat = format.GetFormat("yyyy-MM-dd");return style;}}#endregion}}DemoTest.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DemoTest.aspx.cs" Inherits="NPOIDemo.DemoTest" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"><title></title> </head> <body><form id="form1" runat="server"><div><asp:Button runat="server" ID="btn_Export" Text="導出" OnClick="btn_Export_Click" /></div></form> </body> </html>DemoTest.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using NPOIDemo.Model;namespace NPOIDemo {public partial class DemoTest : System.Web.UI.Page{protected void Page_Load(object sender, EventArgs e){}protected void btn_Export_Click(object sender, EventArgs e){DataTable dt = CreateDataTable();IList<NPOIModel> list = new List<NPOIModel>();list.Add(new NPOIModel(dt, "name;sex;workyear;position;hiredate;skill;hobby;avg", "測試1","姓名#性別#工作情況 工作年限,職位#入職日期#其他信息 能力 技能,愛好#其他信息 年齡", "測試1"));dt = CreateDataTable();list.Add(new NPOIModel(dt, null, "測試2", null, "測試2"));//dt = FarmerList();//list.Add(new NPOIModel(dt, "rowid;tname;vname;Name;IdNumber;education;political;mz;Household;HouseholdType;Phone;Domicile", "測試3",// "所屬鄉鎮 序號,鄉鎮,行政村#所在村 基本信息 姓名,身份證號,文化程度,政治面貌,民族,戶籍,戶籍性質,手機,現居住地", "崇明縣農業從業人員信息統計表"));NPOIHelper.Export(null, list);}//private DataTable FarmerList() {// string sql = @"SELECT TOP 20 ROW_NUMBER()OVER(ORDER BY a.Id) rowid,b.Name tname,c.Name vname,a.Name,a.IdNumber,d.Name education,e.Name political,// '漢族' mz,a.Household,a.HouseholdType,a.Phone,Domicile FROM dbo.tb_FarmerInfo a// LEFT JOIN dbo.View_Area b ON b.id=a.CurrentArea// LEFT JOIN dbo.View_Area c ON c.id=a.InCome// LEFT JOIN dbo.tb_BaseData d ON d.Id=a.Education// LEFT JOIN dbo.tb_BaseData e ON e.Id=a.Political// WHERE a.InCome IS NOT NULL";// return DbHelperSQL.Query(sql).Tables[0];//}private DataTable CreateDataTable(){DataTable dt = new DataTable();DataColumn col = new DataColumn("name", typeof(string));dt.Columns.Add(col);col = new DataColumn("sex", typeof(string));dt.Columns.Add(col);col = new DataColumn("avg", typeof(int));dt.Columns.Add(col);col = new DataColumn("mobilephone", typeof(decimal));dt.Columns.Add(col);col = new DataColumn("workyear", typeof(int));dt.Columns.Add(col);col = new DataColumn("position", typeof(string));dt.Columns.Add(col);col = new DataColumn("skill", typeof(string));dt.Columns.Add(col);col = new DataColumn("hobby", typeof(string));dt.Columns.Add(col);col = new DataColumn("hiredate", typeof(DateTime));dt.Columns.Add(col);DataRow rw = dt.NewRow();rw["name"] = "卡爾";rw["sex"] = "男";rw["avg"] = 20;rw["mobilephone"] = 15800034430;rw["workyear"] = 3;rw["position"] = "程序員";rw["skill"] = ".net,oracel,sqlserver,html5,css3";rw["hobby"] = "打籃球,運動";rw["hiredate"] = DateTime.Now;dt.Rows.Add(rw);rw = dt.NewRow();rw["name"] = "玫瑰";rw["sex"] = "女";rw["avg"] = 23;rw["mobilephone"] = 17800034430;rw["workyear"] = 4;rw["position"] = "美工";rw["skill"] = "ps";rw["hobby"] = "唱歌,跳舞,做飯";rw["hiredate"] = DateTime.Now;dt.Rows.Add(rw);rw = dt.NewRow();rw["name"] = "boss";rw["sex"] = "男";rw["avg"] = 45;rw["mobilephone"] = 13800039980;rw["workyear"] = 20;rw["position"] = "老總";rw["skill"] = "人際關系,企業管理";rw["hobby"] = "爬山,攝影,跑步,游泳";rw["hiredate"] = DateTime.Now;dt.Rows.Add(rw);return dt;}} }運行結果如圖:
總結
以上是生活随笔為你收集整理的使用NPOI导出Excel模板的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Unity][Crowd]学习人群模拟
- 下一篇: Apache Hudi的编译及安装