首页 > 代码库 > 使用NPOI将DataTable生成Excel

使用NPOI将DataTable生成Excel

听闻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 = http://www.mamicode.com/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里的首行显示“名字”这么个列头了。

使用NPOI将DataTable生成Excel