C# NPOI 导出Excel模板


1. winForm 导出 Excel模板

SaveFileDialog fileDialog = new SaveFileDialog();
            fileDialog.Filter = "Excel(97-2003)|*.xls|Excel(2007)|*.xlsx";
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            string sql = "Select* from YSFGGA where GGA001 = 'FT19003955'";
            DataTable dt1 = Common.SQLHelper.ExecuteDataTable(CommandType.Text, sql, null);
            sql = "Select* from YSFGGB where GGB001 = 'FT19003955'";
            DataTable dt2 = Common.SQLHelper.ExecuteDataTable(CommandType.Text, sql, null);
            //-----------------------------------------------------------------------------
            string TempletFileName = @"template\CHUANJIN_INV_TMP.xlsx";      //模板文件  

            FileStream file = null;
            
            try
            {
                file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read);
            }
            catch (Exception ex)
            {
                
                return;
            }
            /// NuGet 管理器下载NPOI
            /// HSSFWorkbook .xls
            //HSSFWorkbook workbook = new HSSFWorkbook(file);
            //ISheet sheet = workbook.CreateSheet("I");
            //IRow rowHead = sheet.CreateRow(0);

            /// XSSFWorkbook excel 2007 .xls 
            XSSFWorkbook xssfworkbook = new XSSFWorkbook(file);
            ISheet sheet = xssfworkbook.GetSheetAt(0);//.CreateSheet();
            //IRow rowHead = sheet.CreateRow(0);
            //填写表头
            //for (int i = 0; i < dt2.Columns.Count; i++)
            //{
            //    break;
            //    rowHead.CreateCell(i, CellType.String).SetCellValue("");
            //}
            //填写内容
            for (int i = 0; i < dt2.Rows.Count; i++)
            {
                //IRow row = sheet.CreateRow(i + 17);
                IRow row = sheet.GetRow(i + 17);
                row.GetCell(1).SetCellValue("这里存放物品编码");// GetCell() 保存模板样式
                row.GetCell(2).SetCellValue("这里存放物品名称");
                row.GetCell(5).SetCellValue(1000);

                //for (int j = 0; j < dt2.Columns.Count; j++)
                //{
                //    row.CreateCell(j, CellType.String).SetCellValue(dataGridView1.Rows[i].Cells[j].Value.ToString());
                //}
            }
            sheet.ForceFormulaRecalculation = true;
            
            using (FileStream stream = File.OpenWrite(fileDialog.FileName))
            {
                xssfworkbook.Write(stream);
                stream.Close();
            }
            MessageBox.Show("导出数据成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            GC.Collect();

相关