首页-玉祥公司客服

标题: WinForm 使用 NPOI 2.2.1从datatable导出Excel [打印本页]

作者: Adam丶鱼    时间: 2020-5-28 18:38
标题: WinForm 使用 NPOI 2.2.1从datatable导出Excel
IWorkbook excel = new HSSFWorkbook();//创建.xls文件
            ISheet sheet = excel.CreateSheet("sheet1"); //创建sheet

            DataTable datatable = (DataTable)dataGridView.DataSource;//获取数据源datatable

            IRow row = sheet.CreateRow(0);//创建行对象,填充表头
            foreach (DataColumn column in datatable.Columns)
            {
                row.CreateCell(0).SetCellValue("供应商编号");
                row.CreateCell(1).SetCellValue("供应商名称");
                row.CreateCell(2).SetCellValue("供应商联系方式");
                row.CreateCell(3).SetCellValue("供应商地址");
                row.CreateCell(4).SetCellValue("供应商税号");
                row.CreateCell(5).SetCellValue("供应商初期应付款");
                row.CreateCell(6).SetCellValue("供应商分类");
                row.CreateCell(7).SetCellValue("供应商分类编号");
            }

            //填充内容,j从1开始,屏蔽掉第一列,循环读取
            for (int i = 0; i < datatable.Rows.Count; i++)
            {
                row = sheet.CreateRow(i + 1);
                for (int j = 1; j < datatable.Columns.Count; j++)
                {
                    row.CreateCell(j-1).SetCellValue(datatable.Rows[i][j].ToString());
                    sheet.AutoSizeColumn(j);
                }
            }

            //写入文件
            string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            FileStream xlsfile = new FileStream(DesktopPath + @"\供应商信息Excel" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls", FileMode.Create);
            excel.Write(xlsfile);
            xlsfile.Close();

            MessageBox.Show("Excel文件已导出到桌面","提示");


作者: Adam丶鱼    时间: 2020-5-28 18:39

作者: 张兴康    时间: 2020-5-29 14:39

作者: fteair    时间: 2020-5-29 14:44

作者: Adam丶鱼    时间: 2020-5-29 18:37
fteair 发表于 2017-6-29 14:44


作者: caixuqad    时间: 2020-6-7 16:32





欢迎光临 首页-玉祥公司客服 (http://plat.delit.cn/) Powered by Discuz! X3.2