我试图将我的数据导出到包含近70000行的Excel工作表中。 我收到以下错误:
线程中的异常" http-bio-8765-exec-1" java.lang.OutOfMemoryError: Java堆空间 在org.apache.xmlbeans.impl.store.Saver $ TextSaver.resize(Saver.java:1700) 在org.apache.xmlbeans.impl.store.Saver $ TextSaver.preEmit(Saver.java:1303) 在org.apache.xmlbeans.impl.store.Saver $ TextSaver.emit(Saver.java:1190)
以下是用于编写Excel的代码:
public String getXLSWriter(ResultSet rs, String file_name)
{
String filepath="";
try {
//String filename=file_name.replace('/','_');
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(file_name);
XSSFRow rowhead = sheet.createRow((int) 0);
filepath=prop.getProperty("file_store_path")+file_name+timeStamp+".xlsx";
FileOutputStream fileOut = new FileOutputStream(filepath);
rowhead.createCell((int) 0).setCellValue("ID");
rowhead.createCell((int) 1).setCellValue("firstName");
rowhead.createCell((int) 2).setCellValue("LastName");
int i = 1;
while (rs.next()){
XSSFRow row = sheet.createRow((int) i);
row.createCell((int) 0).setCellValue(rs.getString("id"));
row.createCell((int) 1).setCellValue(rs.getString("first_name") );
row.createCell((int) 2).setCellValue(rs.getString("last_name"));
i++;
}
workbook.write(fileOut);
fileOut.close();
System.out.println("XLS done!!");
} catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
以下是我用于下载Excel的代码:
public void getDownloaded(String filepath,HttpServletResponse response)
{
try {
File file=new File(filepath);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition","attachment;filename="+file.getName());
FileInputStream in=new FileInputStream(file);
ServletOutputStream out=response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary content to output stream
int length;
while((length=in.read(outputByte, 0, 4096)) != -1){
out.write(outputByte, 0, length);
}
in.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
不要一次读取所有数据,或者在启动java以增加最大内存时使用-Xmx选项。 检查内存泄漏并将数据导入数据库以保存本地内存。