首页 > Windows开发 > 详细

C#利用NPOI在同一个Excel文件中创建多个sheet

时间:2021-04-20 13:43:25      阅读:18      评论:0      收藏:0      [点我收藏+]

借用NPOI来实现,要在同一Excel文件中创建多个sheet,只需要在同一个workbook中创建多个sheet即可。要注意的是,sheet的名字一定不能重复。下面是实现的代码:

 private void buttonTest_Click(object sender, EventArgs e)
        {
            HSSFWorkbook workBook = new HSSFWorkbook();
            //ISheet sheetA = workBook.CreateSheet("sheetA");
            //ISheet sheetB = workBook.CreateSheet("sheetB");

            createSheet(workBook,"SheetA");
            createSheet(workBook,"SheetB");
            createSheet(workBook,"SheetC");

            string path = Application.StartupPath + @"\test.xls";
            if (File.Exists(path))
            {
                File.Delete(path);
            }
            using (FileStream file = new FileStream(path, FileMode.Create))
            {
                workBook.Write(file);  //创建Excel文件。
                file.Close();
            }
            MessageBox.Show("OK");
        }

        private ISheet createSheet(HSSFWorkbook workBook, string sheetName)
        {
            ISheet sheet = workBook.CreateSheet(sheetName);
            IRow RowHead = sheet.CreateRow(0);

            for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
            {
                RowHead.CreateCell(iColumnIndex).SetCellValue(Guid.NewGuid().ToString());
            }

            for (int iRowIndex = 0; iRowIndex < 20; iRowIndex++)
            {
                IRow RowBody = sheet.CreateRow(iRowIndex + 1);
                for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
                {
                    RowBody.CreateCell(iColumnIndex).SetCellValue(DateTime.Now.Millisecond);
                    sheet.AutoSizeColumn(iColumnIndex);
                }
            }
            return sheet;
        }

 

C#利用NPOI在同一个Excel文件中创建多个sheet

原文:https://www.cnblogs.com/leebokeyuan/p/14680420.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!