首页 > 文章列表 > 如何用Java将数据库查询结果导出到Excel表格?

如何用Java将数据库查询结果导出到Excel表格?

352 2024-12-10

如何用Java将数据库查询结果导出到Excel表格?

把查询内容导出到excel表格

如何把数据库中查询到的数据导出到一个有组织的excel文件中?

解决方案

首先,引入必要的poi第三方库。

<!-- 使用apache poi需要的依赖  -->
<dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi</artifactid>
  <version>4.0.1</version>
</dependency>
<dependency>
  <groupid>org.apache.poi</groupid>
  <artifactid>poi-ooxml</artifactid>
  <version>4.0.1</version>
</dependency>
<dependency>
  <groupid>org.apache.commons</groupid>
  <artifactid>commons-compress</artifactid>
  <version>1.19</version>
</dependency>

<!-- 使用druid连接池建立java程序与mysql数据库的连接需要的依赖  -->
<dependency>
  <groupid>mysql</groupid>
  <artifactid>mysql-connector-java</artifactid>
  <version>5.1.26</version>
</dependency>
<dependency>
  <groupid>com.alibaba</groupid>
  <artifactid>druid</artifactid>
  <version>1.0.9</version>
</dependency>

然后,通过以下步骤将数据写入excel:

  1. 创建一个工作簿。
  2. 创建一个表。
  3. 为表创建行和单元格,并将数据插入单元格中。
  4. 创建一个输出流,并将其写入磁盘。

以下是示例代码:

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteExcelTest {
    public static void main(String[] args) {

        XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
        XSSFSheet xssfSheet = xssfWorkbook.createSheet("first_sheet");
        XSSFRow row1 = xssfSheet.createRow(0);
        XSSFRow row2 = xssfSheet.createRow(1);
        XSSFRow row3 = xssfSheet.createRow(2);
        XSSFRow row4 = xssfSheet.createRow(3);

        row1.createCell(0).setCellValue("姓名");
        row1.createCell(1).setCellValue("年龄");
        row1.createCell(2).setCellValue("性别");

        row2.createCell(0).setCellValue("张三");
        row2.createCell(1).setCellValue("18");
        row2.createCell(2).setCellValue("男");

        row3.createCell(0).setCellValue("李四");
        row3.createCell(1).setCellValue("17");
        row3.createCell(2).setCellValue("男");

        row4.createCell(0).setCellValue("黄蓉");
        row4.createCell(1).setCellValue("20");
        row4.createCell(2).setCellValue("女");

        FileOutputStream fileOutputStream = new FileOutputStream("D:/output.xlsx");
        xssfWorkbook.write(fileOutputStream);

        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (xssfWorkbook != null) {
                xssfWorkbook.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("输出成功!");
    }
}
来源:1733009495