package test;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import java.io.FileOutputStream;
import java.sql.*;
public class BigDataExcelOutWrite {
public static String driver="com.mysql.jdbc.Driver";
public static String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8";
public static String username = "root";
public static String password = "root";
/**
* 数据库连接操作
*/
public static Connection getConnection() throws Exception {
// 使用jdbc链接数据库
Class.forName(driver).newInstance();
// 获取数据库连接
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
/**
* @Description: 执行导出Excel操作
*/
public boolean WriteExcel(boolean isClose) {
String excelFile = "D:\\test\\test.xlsx";
// 内存中只创建100个对象,写临时文件,当超过100条,就将内存中不用的对象释放。
SXSSFWorkbook wb = new SXSSFWorkbook(100);
Sheet sheet = null; // 工作表对象
Row nRow = null; // 行对象
Cell nCell = null; // 列对象
try {
Connection conn = getConnection();
Statement stmt = conn.createStatement();
String sql="";
ResultSet rs = stmt.executeQuery(sql); // 获取u_id_number结果
ResultSetMetaData rsmd = rs.getMetaData(); // 获取执行结果的结构(rs.getMetaData().getTableName(1))就可以返回表名,rs.getMetaData().getColumnCount())
long startTime = System.currentTimeMillis();
System.out.println("开始执行时间 : " + startTime / 1000 + "m");
int rowNo = 0; // 总行号
int pageRowNo = 0; // 页行号
while (rs.next()) {
// 打印500000条后切换到下个工作表,可根据需要自行拓展,2百万,3百万...数据一样操作,只要不超过1048576就可以
if (rowNo % 500000 == 0) {
System.out.println("当前sheet页为:" + rowNo / 500000 );
sheet = wb.createSheet("我的第" + (rowNo / 500000 + 1) + "个工作簿");// 建立新的sheet对象
sheet = wb.getSheetAt(rowNo / 500000); // 动态指定当前的工作表
pageRowNo = 1; // 每当新建了工作表就将当前工作表的行号重置为1
//定义表头
nRow = sheet.createRow(0);
}
rowNo++;
nRow = sheet.createRow(pageRowNo++); // 新建行对象
// 打印每行,每行有6列数据 rsmd.getColumnCount()==6 --- 列属性的个数
for (int i = 0; i < rsmd.getColumnCount(); i++) {
nCell = nRow.createCell(i);
nCell.setCellValue(rs.getString(i + 1));
}
if (rowNo % 10000 == 0) {
System.out.println("row no: " + rowNo);
}
}
long finishedTime = System.currentTimeMillis(); // 处理完成时间
System.out.println("数据读取完成耗时 : " + (finishedTime - startTime) / 1000 + "m");
FileOutputStream fOut = new FileOutputStream(excelFile);//将数据写入Excel
wb.write(fOut);
fOut.flush(); // 刷新缓冲区
fOut.close();
long stopTime = System.currentTimeMillis(); // 写文件时间
System.out.println("数据写入Excel表格中耗时 : " + (stopTime - startTime) / 1000 + "m");
if (isClose) {
this.close(rs, stmt, conn);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
// 执行关闭流的操作
private void close(ResultSet rs, Statement stmt, Connection conn)throws SQLException {
rs.close();
stmt.close();
conn.close();
}
//测试方法
public static void main(String[] args) {
BigDataExcelOutWrite bdeo = new BigDataExcelOutWrite();
bdeo.WriteExcel(true);
}
}