POI 的 Maven 依赖:
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
代码:
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.FileOutputStream;
import java.sql.ResultSet;
/**
* Author: htd
* Date: 2018/3/15
* Desc: 将 Hive 查询返回的 ResultSet 输出到 Excel 中
*/
public class ResultSetOutputExcelUtil {
public static void toExcel(ResultSet rs, String outName) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("sheet");
HSSFRow row = sheet.createRow(0);
HSSFCell cell;
for (int j = 0; j < rs.getMetaData().getColumnCount(); ++j) {
String colName = rs.getMetaData().getColumnLabel(j + 1);
cell = row.createCell(j);
cell.setCellValue(colName);
}
int i = 0;
while (rs.next()) {
row = sheet.createRow(i + 1);
for (int j = 0; j < rs.getMetaData().getColumnCount(); ++j) {
String c = rs.getString(j + 1);
row.createCell(j).setCellValue(c);
}
++i;
}
FileOutputStream foStream = new FileOutputStream(outName);
wb.write(foStream);
foStream.flush();
foStream.close();
}
}
输入参数为: ResultSet 和 输出文件的名称(包括路径)
3、Exporting Resultset from Java database to Excel using Apache Poi
https://stackoverflow.com/questions/24933868/exporting-resultset-from-java-database-to-excel-using-apache-poi