java - 冲刺启动中的多个 Excel 文件
问题描述
有没有办法通过spring boot创建多个excel文件而不是多个工作表?我一直在使用 apache poi 来生成 excel。
@GetMapping("/export/excel")
public void exportToExcel(HttpServletResponse response) throws IOException {
response.setContentType("application/octet-stream");
String headerKey = "Content-Disposition";
String headervalue = "attachment; filename=Customer.xlsx";
response.setHeader(headerKey, headervalue);
List<cusEntity> data1= customerRepo.fetchEmailData();
UserExcelExporter exp = new UserExcelExporter(data1);
exp.export(response);
}
public class UserExcelExporter {
private XSSFWorkbook workbook;
private XSSFSheet sheet;
private List<EmailDataEntity> listClients;
public UserExcelExporter(List<cusEntity> listClients) {
this.listClients=listClients;
workbook = new XSSFWorkbook();
}
private void createCell(Row row, int columnCount, Object value, CellStyle style) {
sheet.autoSizeColumn(columnCount);
Cell cell=row.createCell(columnCount);
if(value instanceof Long) {
cell.setCellValue((Long) value);
}else if(value instanceof Integer) {
cell.setCellValue((Integer) value);
}else if(value instanceof Boolean) {
cell.setCellValue((Boolean) value);
}else {
cell.setCellValue((String) value);
}
cell.setCellStyle(style);
}
private void writeHeaderLine(String iteration) {
sheet = workbook.createSheet("Report");
Row row = sheet.createRow(0);
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
createCell(row,0,"Trust & Agency Service",style);
sheet.addMergedRegion(new CellRangeAddress(0,0,0,6));
font.setFontHeightInPoints((short)(10));
}
private void writeDataLines() {
int rowCount=1;
CellStyle style=workbook.createCellStyle();
XSSFFont font=workbook.createFont();
font.setFontHeight(14);
style.setFont(font);
for(cusEntity client:listClients) {
Row row=sheet.createRow(rowCount++);
int columnCount=0;
createCell(row, columnCount++, client.getname(), style);
}
}
public void export(HttpServletResponse response,String iteration) throws IOException{
writeHeaderLine(iteration);
writeDataLines();
ServletOutputStream outputStream=response.getOutputStream();
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
}
当我尝试重复 exp.export(response) 的代码时,它给了我 1 个 excel,对于下一个 excel,它说工作簿已经包含一个名为“报告”的工作表。我认为如果它创建了 2 个 excel,那么具有相同的工作表名称应该不是问题。但似乎它试图创建另一个工作表而不是另一个 excel 。如果我错了,请纠正我。
感谢团队。
解决方案
我这样做的方法是更改输出流:并从 HomeController 传递文件名
OutputStream outputStream = new FileOutputStream(String.format("C:\\Users\\kasis\\ExcelFolder\\%s.xlsx",fileName));
推荐阅读
- android - 服务内的 Android 版 MapBox
- oracle - 我在哪里可以找到 Oracle Cloud 中的 Rest API Endpoint?
- asp.net - ADFS 本机应用程序访问令牌缺少声明
- node.js - 从节点 js 服务器文件向浏览器添加 cookie
- vue.js - 带有 Vue 的电子应用程序抛出未捕获的错误:ENOENT
- c# - 动态添加的组合框项目对象不会引发更改通知
- spring-boot - 为什么 Spring Integration 中的 TIMESTAMP 和 ID 标头在 Spring Kafka 中未映射?
- sql - Oracle Sql - 今天获取查询结果比昨天慢得多
- java - 无法解析方法 getBaseContext()
- linq - 访问 linq 查询表变量中的属性值