写一个.net 6的API接口,使用c#语言调用NPOI生成多个Excel文件,每个Excel文件中都包含多个Sheet,表中标题为“我是标题”,标题格式为加粗合并居中,每个sheet里,都要在数据满7行时,空两行再将标题和表头重复一次。所有Excel文件都存为xls格式。
效果:
代码操作:
源码:
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.IO;
namespace ExcelApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class ExcelController : ControllerBase
{
private const string ExcelFolder = "./GeneratedExcelFiles/";
[HttpPost("generate")]
public IActionResult GenerateExcelFiles()
{
try
{
// Create a folder for storing generated Excel files if not exists
Directory.CreateDirectory(ExcelFolder);
// Generate multiple Excel files with multiple sheets
for (int fileIndex = 1; fileIndex <= 3; fileIndex++) // Example: Generate 3 Excel files
{
string fileName = $"File{
fileIndex}.xls";
string filePath = Path.Combine(ExcelFolder, fileName);
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new HSSFWorkbook();
for (int sheetIndex = 1; sheetIndex <= 2; sheetIndex++) // Example: Each file has 2 sheets
{
string sheetName = $"Sheet{
sheetIndex}";
ISheet sheet = workbook.CreateSheet(sheetName);
// Add title row
IRow titleRow = sheet.CreateRow(0);
titleRow.HeightInPoints = 30;
ICell titleCell = titleRow.CreateCell(0);
titleCell.SetCellValue("我是标题");
// Style for title
var titleStyle = workbook.CreateCellStyle();
var titleFont = workbook.CreateFont();
titleFont.Boldweight = (short)FontBoldWeight.Bold;
titleStyle.