我有一个场景,我想写一个值对象列表,如:
public class RequestHandlerVo {
private String userSoeID;
private String email;
private String firstName;
private String lastName;
private String publicationReceived;
private String sourceOfUnsubscribe;
private String senderEmail;
private String receivedDateFrom;
private String receivedDateTo;
private String apiName;
private String updatedBy;
private String updatedOn;
private String action;
}
在不使用此逻辑的情况下进入excelsheet:
Set<Integer> keyset = hashmap.keySet();
InputStream inp = new FileInputStream( new File(path));
FileOutputStream out = new FileOutputStream( new File(path));
int rownum = 1;
int cellnum = 0;
initializeExcelFile(hashmap,path);
workbook = new XSSFWorkbook(inp);
XSSFSheet sheet = workbook.getSheetAt(0);
for(Integer key : keyset){
List<String> nameList = hashmap.get(key);
for(String s : nameList){
XSSFRow row = sheet.getRow(rownum++);
Cell cell = row.getCell(cellnum);
if(null!=cell){
cell.setCellValue(s);
}
}
cellnum++;
rownum=1;
}
workbook.write(out);
因为我有成千上万的记录,这个逻辑导致我超过100k次迭代。在excel文件中写入1035条记录需要92秒。
我经历过: this,Write data into Excel sheet java和How list has map values write to excel file using Apache poi
但没有得到解决方案。
答案 0 :(得分:0)
如果你对CSV或其他文件格式没问题,你可以试试这个。下面的示例使用单行代码从ArrayList写入CSV文件。
您可以根据输入源类型对其进行修改。
ArrayList<String> data = new ArrayList<String>();
// add data to arrray list
Path out = Paths.get("filename.csv");
Files.write(out, data, Charset.defaultCharset());