当前位置: 首页 > 工具软件 > Npoi.Mapper > 使用案例 >

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

庄瀚玥
2023-12-01

https://www.bbsmax.com/A/E35pB6wRzv/

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

 
  1. private void buttonTest_Click(object sender, EventArgs e)
  2. {
  3. HSSFWorkbook workBook = new HSSFWorkbook();
  4. //ISheet sheetA = workBook.CreateSheet("sheetA");
  5. //ISheet sheetB = workBook.CreateSheet("sheetB");
  6. createSheet(workBook,"SheetA");
  7. createSheet(workBook,"SheetB");
  8. createSheet(workBook,"SheetC");
  9. string path = Application.StartupPath + @"\test.xls";
  10. if (File.Exists(path))
  11. {
  12. File.Delete(path);
  13. }
  14. using (FileStream file = new FileStream(path, FileMode.Create))
  15. {
  16. workBook.Write(file);  //创建Excel文件。
  17. file.Close();
  18. }
  19. MessageBox.Show("OK");
  20. }
  21. private ISheet createSheet(HSSFWorkbook workBook, string sheetName)
  22. {
  23. ISheet sheet = workBook.CreateSheet(sheetName);
  24. IRow RowHead = sheet.CreateRow(0);
  25. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  26. {
  27. RowHead.CreateCell(iColumnIndex).SetCellValue(Guid.NewGuid().ToString());
  28. }
  29. for (int iRowIndex = 0; iRowIndex < 20; iRowIndex++)
  30. {
  31. IRow RowBody = sheet.CreateRow(iRowIndex + 1);
  32. for (int iColumnIndex = 0; iColumnIndex < 10; iColumnIndex++)
  33. {
  34. RowBody.CreateCell(iColumnIndex).SetCellValue(DateTime.Now.Millisecond);
  35. sheet.AutoSizeColumn(iColumnIndex);
  36. }
  37. }
  38. return sheet;
  39. }
 类似资料: