C# 使用NPOI生成Excel文件
nuget 引入NPOI
IWorkbook wk = new HSSFWorkbook(); // 设置样式 ICellStyle cellStyle = wk.CreateCellStyle(); cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; cellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; // 创建Sheet ISheet sheet = wk.CreateSheet("报文数据"); // 设置单元的宽度 sheet.SetColumnWidth(0, 10 * 256); sheet.SetColumnWidth(1, 15 * 256); sheet.SetColumnWidth(2, 15 * 256); sheet.SetColumnWidth(3, 15 * 256); sheet.SetColumnWidth(4, 65 * 256); // 写入一行数据 int rowIndex = 0; IRow row = sheet.CreateRow(rowIndex); row.CreateCell(0).SetCellValue("序号"); row.CreateCell(1).SetCellValue("时间"); row.CreateCell(2).SetCellValue("名称"); row.CreateCell(3).SetCellValue("帧ID(HEX)"); row.CreateCell(4).SetCellValue("数据(HEX)"); row.CreateCell(5).SetCellValue(" "); rowIndex++; // 循环写入数据 for (int i = 0; i < 100; i++) { row = sheet.CreateRow(rowIndex); row.CreateCell(0).SetCellValue(rowIndex); rowIndex++; } // 生成文件,写入数据 (确保你文件夹存在) using (FileStream fswrite = File.OpenWrite($"Excel/test/test.xls")) { wk.Write(fswrite); }
结果