winform NPOI excel 导出并选择保存文件路径

时间:2021-07-07 07:12:24
        public void ExcelOp(DataGridView gdv,ArrayList selHead)
        {
            if (selHead.Count==0)
            {
                MessageBox.Show("没有数据,无法导出EXCEL!");
                return;
            }

            IWorkbook excel = new HSSFWorkbook();//创建.xls文件
            ISheet sheet = excel.CreateSheet("sheet1"); //创建sheet
            IRow row = sheet.CreateRow(0);
            //创建行对象,填充表头
            row.CreateCell(0).SetCellValue("月份");
            row.CreateCell(1).SetCellValue("门\\病");
            row.CreateCell(2).SetCellValue("科别");
            row.CreateCell(3).SetCellValue("收入类别");
            row.CreateCell(4).SetCellValue("姓名");
            
            //写入文件 弹出文件保存
            //string DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//桌面路径
            string filename = statistics_head.Text+ printDetailClass.GetUnixTime(DateTime.Now).ToString();//文件名
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = filename;
            saveDialog.ShowDialog();
            filename = saveDialog.FileName;
            if (filename.IndexOf(":") < 0) return; //被点了取消
            FileStream xlsfile = new FileStream(saveDialog.FileName, FileMode.Create);
            excel.Write(xlsfile);
            xlsfile.Close();
            System.Diagnostics.Process.Start(filename);
        }