NPOI 导出Excel

 

Npoi导出excel在项目中经常用到,记录到博客园,需要的时候直接copy

数据源为 Datatable

public MemoryStream RenderToExcel(DataTable table)
        {
            MemoryStream ms = new MemoryStream();

            using (table)
            {
                IWorkbook workbook = new HSSFWorkbook();
                ISheet sheet = workbook.CreateSheet();

                IRow headerRow = sheet.CreateRow(0);

                // handling header.
                foreach (DataColumn column in table.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

                // handling value.
                int rowIndex = 1;

                foreach (DataRow row in table.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);

                    foreach (DataColumn column in table.Columns)
                    {
              //根据字段格式,确定excel单元格的显示格式
              dataRow.CreateCell(column.Ordinal).SetCellType(CellType.String); dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex
++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; } return ms; }      //写到磁盘上 private void SaveToFile(MemoryStream ms, string fileName) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); data = null; } }

 

posted on 2014-08-11 14:37  忙碌ing  阅读(215)  评论(0)    收藏  举报

导航