聽聞npoi 2.0版本支持excel2007格式了,表示期待其表現。不過目前還是使用1.2.5穩重點。
生活中有太多的列表都需要一個導出功能,當然這裡的生活指的的程序員的生活。DataTable是從數據庫讀取數據後常用的數據結構,又當然這裡的DataTable是指.Net開發下的。今天剛好做了個導出excel的功能,於是乎就在完成功能後把該方法抽離出來做成一個類,以備後用。整個類如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS.UserModel; using NPOI.HSSF.UserModel; using System.Data; using System.IO; namespace Excel { public class ExcelHelper { /// <summary> /// 類版本 /// </summary> public string version { get { return "0.1"; } } readonly int EXCEL03_MaxRow = 65535; /// <summary> /// 將DataTable轉換為excel2003格式。 /// </summary> /// <param name="dt"></param> /// <returns></returns> public byte[] DataTable2Excel(DataTable dt, string sheetName) { IWorkbook book = new HSSFWorkbook(); if (dt.Rows.Count < EXCEL03_MaxRow) DataWrite2Sheet(dt, 0, dt.Rows.Count - 1, book, sheetName); else { int page = dt.Rows.Count / EXCEL03_MaxRow; for (int i = 0; i < page; i++) { int start = i * EXCEL03_MaxRow; int end = (i * EXCEL03_MaxRow) + EXCEL03_MaxRow - 1; DataWrite2Sheet(dt, start, end, book, sheetName + i.ToString()); } int lastPageItemCount = dt.Rows.Count % EXCEL03_MaxRow; DataWrite2Sheet(dt, dt.Rows.Count - lastPageItemCount, lastPageItemCount, book, sheetName + page.ToString()); } MemoryStream ms = new MemoryStream(); book.Write(ms); return ms.ToArray(); } private void DataWrite2Sheet(DataTable dt, int startRow, int endRow, IWorkbook book,string sheetName) { ISheet sheet = book.CreateSheet(sheetName); IRow header = sheet.CreateRow(0); for (int i = 0; i < dt.Columns.Count; i++) { ICell cell = header.CreateCell(i); string val = dt.Columns[i].Caption ?? dt.Columns[i].ColumnName; cell.SetCellValue(val); } int rowIndex = 1; for (int i = startRow; i <= endRow; i++) { DataRow dtRow = dt.Rows[i]; IRow excelRow = sheet.CreateRow(rowIndex++); for (int j = 0; j < dtRow.ItemArray.Length; j++) { excelRow.CreateCell(j).SetCellValue(dtRow[j].ToString()); } } } } }
該類實現將DataTable轉化為excel2003的二進制格式,如果DataTable的行數超過了excel2003的最大行數限制,還會分成多個sheet表。
使用示例則如下:
public void test() { DataTable dt = new DataTable(); DataColumn[] cols = new DataColumn[] { new DataColumn("name",typeof(string)), new DataColumn ("birthday",typeof(DateTime)), new DataColumn ("score",typeof(int)) }; dt.Columns.AddRange(cols); Random rnd = new Random(); for (int i = 0; i < 10; i++) { DataRow row = dt.NewRow(); object[] items = new object[] { "小明", DateTime.Now , rnd.Next(100) }; row.ItemArray = items; dt.Rows.Add(row); } myExcelLib.ExcelHelper myhelper = new myExcelLib.ExcelHelper(); byte[] data = myhelper.DataTable2Excel(dt,"人員名錄"); string path = "d:\\temp" + DateTime.Now.Ticks.ToString() + ".xls"; if (!File.Exists(path)) { FileStream fs = new FileStream(path, FileMode.CreateNew); fs.Write(data, 0, data.Length); fs.Close(); } }
看完碼,接下來且聽我解釋:
整個ExcelHelper的類只提供了一個公共函數DataTable2Excel,參數也很簡單,就把DataTable和一個將生成的sheet表名傳過去便可。不過我們導出的excel表第一行通常都是列頭名稱,例如數據裡的列名是“name”,但是我們需要顯示在excel裡頭是“名字”,所以這裡的DataTable還需要稍加修飾,例如dt.columns[“name”].Caption=”名字”。這樣會在生成的excel裡的首行顯示“名字”這麼個列頭了。