Java Apache POI和JDBC:将大量数据导入Excel的智能方法
发布时间:2020-12-15 02:13:59 所属栏目:Java 来源:网络整理
导读:参见英文答案 Writing a large resultset to an Excel file using POI????????????????????????????????????6个 我想使用Java Apache POI和Oracle JDBC从Oracle数据库中获取大量数据(超过100.000行,包含50列)到Excel文件中.这对于少量数据很有效,但处理这样
参见英文答案 >
Writing a large resultset to an Excel file using POI????????????????????????????????????6个
我想使用Java Apache POI和Oracle JDBC从Oracle数据库中获取大量数据(超过100.000行,包含50列)到Excel文件中.这对于少量数据很有效,但处理这样的任务的最聪明方法是什么?也许使用多线程?我得到像“java.lang.OutOfMemoryError:Java堆空间”这样的错误,虽然我已经将内存增加到1024MB. 这是我目前的代码: public void fetchDataIntoExcelFile(String sqlStmt){ // Check whether jdbc driver exists or not try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { System.out.println("Please install the Oracle JDBC Driver!"); e.printStackTrace(); return; } // Try to establish a connection to the db try { conn = DriverManager.getConnection("jdbc:oracle:thin:@myserver","user","password"); } catch (SQLException e) { e.printStackTrace(); return; } XSSFWorkbook wbx = new XSSFWorkbook(); XSSFSheet sheet = wbx.createSheet(); FileOutputStream fos = null; try { fos = new FileOutputStream("filename.xlsx"); wbx.write(fos); } catch (IOException e) { e.printStackTrace(); System.out.println("Error occured while creating file."); } // Execute SQL Statement if connection was successful if (conn != null) { try { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sqlStmt); ResultSetMetaData columns = rs.getMetaData(); XSSFRow row = null; XSSFCell cell = null; // Start writing results into the excel file int i = 0; while (rs.next()){ row = sheet.createRow(i++); for (int j = 1; j <= columns.getColumnCount(); j++){ cell = row.createCell(j); if (i == 1){ cell.setCellValue(columns.getColumnLabel(j)); }else{ cell.setCellValue(rs.getString(columns.getColumnLabel(j))); } } } try { wbx.write(fos); fos.close(); } catch (IOException e) { e.printStackTrace(); } } catch (SQLException e) { System.out.println("Connection Failed!"); e.printStackTrace(); return; } } else { System.out.println("Failed to make connection!"); } } 解决方法
它有助于按照建议使用SXSSF API.链接在这里:
https://poi.apache.org/spreadsheet/how-to.html#sxssf (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |