gpt4 book ai didi

java - 在 Spring 为 excel 生成运行一个短暂的后台任务

转载 作者:行者123 更新时间:2023-11-29 09:31:57 24 4
gpt4 key购买 nike

在我的项目中,要求是在后台进程中生成 EXCEL 文件(我用 POI 完成了)。当用户单击 excel generate 时,后台进程将运行并生成 excel 并通知用户 excel 已准备好下载(使用 Velocity 完成)。我有 20 多个任务需要生成一个 excel 文件。所有任务都应在后台运行,以便用户可以顺利访问整个应用程序。我们用来获取 excel 文件数据的数据库是 MYSQL

提前致谢。

最佳答案

enter image description here新建一个excel文件

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
//..
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
//Create a new row in current sheet
Row row = sheet.createRow(0);
//Create a new cell in current row
Cell cell = row.createCell(0);
//Set value to new value
cell.setCellValue("Blahblah");

下面是用虚拟数据编写一个新的 excel 的完整代码:

HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");

Map<string, object[]=""> data = new HashMap<string, object[]="">();
data.put("1", new Object[] {"Emp No.", "Name", "Salary"});
data.put("2", new Object[] {1d, "John", 1500000d});
data.put("3", new Object[] {2d, "Sam", 800000d});
data.put("4", new Object[] {3d, "Dean", 700000d});

Set<string> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}

try {
FileOutputStream out =
new FileOutputStream(new File("C:\\new.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

关于java - 在 Spring 为 excel 生成运行一个短暂的后台任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30524389/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com