Webapp to provide csv report for user to download. I'm having issue when there is millions of rows in table to write it to the response.
I tried to select by batch(using rowNum), since putting too much of object into arraylist will lead to out of memory issue. But still, setting too much data into stringbuilder will hit out of memory issue as well.
Here is the code use to downloadCSV:
public void downloadCSV(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
long totalRecordCnt = getTotalRecords(batchId, ...);
int range = 10000;
BufferedOutputStream bos = null;
try {
StringBuilder tableStr = new StringBuilder();
bos = new BufferedOutputStream(response.getOutputStream());
tableStr.append('\ufeff');
tableStr.append("\"" + ....);
tableStr.append("Batch ID" + ","
+"User Name" + "," + "Acc balance" + "\n");
// split the records into smaller batch to process
if (totalRecordCnt > 0) {
long totalBatchCnt = totalRecordCnt / range;
if (totalRecordCnt % range > 0) {
totalBatchCnt += 1;
}
long totalRecordCntTemp = totalRecordCnt;
for (int i = 1; i <= totalBatchCnt; i++) {
long endRange = 0;
long startRange = ((i - 1) * range) + 1L;
if (totalRecordCntTemp < range) {
endRange = totalRecordCnt;
} else {
endRange = startRange + range - 1;
}
totalRecordCntTemp = totalRecordCntTemp - range;
// process records
List<Account> account = null;
account = getAccountList(batchId, startRange,endRange);
if (account != null && !account.isEmpty()) {
for (Account acc : account) {
tableStr.append("\"" + acc.getBatchId + "\",\"" + accnt.getName
+ "\"" + "\n");
}
}
}
}
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
String csvFileName = "Acc_report" + ".csv";
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + csvFileName);
bos.write(tableStr.toString().getBytes());// Write individual
// field
// followed
bos.flush();
} catch (Exception e) {
throw new IOException(e.getMessage());
} finally {
if (bos != null) {
try {
bos.close();
} catch (Exception e) {
}
}
}
}
Expected: To be able to generate report contains millions of rows instantly once using click on download button.