ApachePOI实现数据库导出到Excel /** * @Description: poi实现输出信息到excel文件 * @Author: nutony * @Date: 2013-05-15 */public class Test3SXSSF {public static void main(String[] args) throws Exception {Test3SXSSF tm = new Tes
/**
* @Description: poi实现输出信息到excel文件
* @Author: nutony
* @Date: 2013-05-15
*/
public class Test3SXSSF {
public static void main(String[] args) throws Exception {
Test3SXSSF tm = new Test3SXSSF();
tm.jdbcex(true);
}
@Test
public void jdbcex(boolean isClose) throws InstantiationException, IllegalAccessException, ClassNotFoundException,
SQLException, IOException, InterruptedException {
String xlsFile = "D:/userInfo.xlsx"; //输出文件
Workbook wb = new SXSSFWorkbook(100); //创建excel文件,内存只有100条记录【关键语句】
Sheet sheet = wb.createSheet("用户信息"); //建立新的sheet对象
Row nRow = null;
Cell nCell = null;
//使用jdbc链接数据库
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8";
String user = "root";
String password = "admin";
Connection conn = DriverManager.getConnection(url, user,password);
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
//如果数量多请分次读取
String sql = "select * FROM user";
ResultSet rs = stmt.executeQuery(sql);
long startTime = System.currentTimeMillis(); //记录开始时间
System.out.println("strat execute time: " + startTime);
//context
int rowNo = 0;
int colNo = 0;
while(rs.next()) {
colNo = 0;
nRow = sheet.createRow(rowNo++);
nCell = nRow.createCell(colNo++);
nCell.setCellValue(rs.getString(colNo));
nCell = nRow.createCell(colNo++);
nCell.setCellValue(rs.getString(colNo));
if(rowNo%100==0){
System.out.println("row no: " + rowNo);
}
//休息一下,防止CPU被占用
Thread.sleep(10);
}
long finishedTime = System.currentTimeMillis(); //记录处理完成时间
System.out.println("finished execute time: " + (finishedTime - startTime)/1000 + "m");
FileOutputStream fOut = new FileOutputStream(xlsFile);
wb.write(fOut);
fOut.flush();
fOut.close();
long stopTime = System.currentTimeMillis(); //写文件时间
System.out.println("write xlsx file time: " + (stopTime - startTime)/1000 + "m");
if(isClose){
this.close(rs, stmt, conn);
}
}
//close resource
private void close(ResultSet rs, Statement stmt, Connection conn ) throws SQLException{
rs.close();
stmt.close();
conn.close();
}
}
