C#利用NPOI在同一個Excel文件中創建多個sheet


借用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;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM