NPOI导出生成Excel文档

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;

 /// <summary>

        /// 导出数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtExport_Click(object sender, EventArgs e)
        {
            DataTable DT = new DataTable();
            string localFilePath = String.Empty;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            //设置文件类型  
            saveFileDialog1.Filter = " xls files(*.xls)|*.txt|All files(*.*)|*.*";
            //设置文件名称:
            saveFileDialog1.FileName = DateTime.Now.ToString("yyyyMMdd") + "-" + "警力数据.xls";

            //设置默认文件类型显示顺序  
            saveFileDialog1.FilterIndex = 2;

            //保存对话框是否记忆上次打开的目录  
            saveFileDialog1.RestoreDirectory = true;

            //点了保存按钮进入  
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                string File = saveFileDialog1.FileName;
                DT = BLL.exportMethod();
                AlertBLL.SaveToExcel(DT, File);
            }

        }

   public static void SaveToExcel(System.Data.DataTable dt, string strXLS)
        {
            if (dt == null || dt.Rows.Count == 0)
                return;
            MemoryStream ms = new MemoryStream();
            IWorkbook workbook = new HSSFWorkbook();//创建Workbook对象

            ISheet mysheet = workbook.CreateSheet();//创建工作表
            IRow row = mysheet.CreateRow(0);
            for (int c = 0; c < dt.Columns.Count; ++c)
            {
                ICell cell = row.CreateCell(c);//在行中添加一列
                cell.SetCellValue(dt.Columns[c].ColumnName);//设置列的内容
            }
            for (int r = 0; r < dt.Rows.Count; ++r)
            {
                row = mysheet.CreateRow(r + 1);//在工作表中添加一行
                for (int c = 0; c < dt.Columns.Count; ++c)
                {
                    ICell cell = row.CreateCell(c);//在行中添加一列
                    cell.SetCellValue(dt.Rows[r][c].ToString());//设置列的内容
                }
            }
            workbook.Write(ms);
            ms.Flush();
            ms.Position = 0;
            SaveToFile(ms, strXLS);
            ms.Close();
        }

        public static 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;
            }
        }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值