使用 POI 将 JDBC 的 ResultSet 导入到 Excel 文件中的方法

POI 的 Maven 依赖:

            <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>3.17</version>
            </dependency>
1
2
3
4
5
6
代码:

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:  yangyingqian
 * 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();

    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
输入参数为: ResultSet 和 输出文件的名称(包括路径)

参考资料:

1、通用的JDBC ResultSet 结果通过POI输出到excel 文件并保存 
https://my.oschina.net/jingshishengxu/blog/1039385

2、利用POI将数据库表导出到Excel 
http://blog.csdn.net/drjerry/article/details/47782881

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
--------------------- 
作者:HeatDeath 
来源:CSDN 
原文:https://blog.csdn.net/HeatDeath/article/details/79578858 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/zhousenshan/article/details/88378987