NPOI操作excel之写入数据到excel表

在上一篇《NPOI操作excel之读取excel数据》我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中。

using System;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;

namespace NPOIOprateExcel
{
    public class ExcelUtility
    {
        public static bool DataTableToExcel(DataTable dt)
        {
            bool result = false;
            IWorkbook workbook = null;
            FileStream fs = null;
            IRow row = null;
            ISheet sheet = null;
            ICell cell = null;
            try
            {
                if (dt != null && dt.Rows.Count > 0)
                {

              //大批量数据导出的时候,需要注意这样的一个问题,Excel2003格式一个sheet只支持65536行,excel 2007 就比较多,是1048576

              //需要ICSharpCode.SharpZipLib.dll库
              //workbook = new HSSFWorkbook(fs);//2003版本.xls
              workbook = new XSSFWorkbook(fs);// 2007版本.xlsx(保存的数据库大)

                    sheet = workbook.CreateSheet("Sheet0");//创建一个名称为Sheet0的表
                    int rowCount = dt.Rows.Count;//行数
                    int columnCount = dt.Columns.Count;//列数

                    //设置列头
                    row = sheet.CreateRow(0);//excel第一行设为列头
                    for (int c = 0; c < columnCount; c++)
                    {
                        cell = row.CreateCell(c);
                        cell.SetCellValue(dt.Columns[c].ColumnName);
                    }                    

                    //设置每行每列的单元格,
                    for (int i = 0; i <rowCount; i++)
                    {
                        row = sheet.CreateRow(i+1);
                        for (int j = 0; j < columnCount; j++)
                        {                            
                            cell = row.CreateCell(j);//excel第二行开始写入数据
                            cell.SetCellValue(dt.Rows[i][j].ToString());                            
                        }
                    }
                    using (fs = File.OpenWrite(@"D:/myxls.xls")) 
                    {
                        workbook.Write(fs);//向打开的这个xls文件中写入数据
                        result = true;
                    }
                }
                return result;
            }
            catch (Exception ex)
            {
                if (fs != null)
                {
                    fs.Close();
                }
                return false;
            }
        }
    }
}

结果如下:

原文地址:https://www.cnblogs.com/qk2014/p/5021613.html