使用POI将数据库中的数据导入到Excel中

news/2024/7/21 7:51:42 标签: poi, Excel

准备工作:

  • 创建表和数据
-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role`  (
  `ID` int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '角色ID',
  `NAME` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '角色名称',
  `COMMENT` varchar(2048) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '角色说明',
  `CREATOR_ID` int(10) UNSIGNED NOT NULL DEFAULT 0 COMMENT '角色创建者ID',
  `CREATE_TIME` datetime(0) NOT NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '角色创建日期',
  PRIMARY KEY (`ID`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '角色表' ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES (1, 'ADMIN', '管理员', 10, '2020-12-25 09:58:14');
INSERT INTO `sys_role` VALUES (2, 'SALES', '销售员', 30, '2020-12-25 09:58:40');

创建一个Maven项目

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>fun.gosuncn</groupId>
    <artifactId>poi</artifactId>
    <version>1.0</version>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>

</project>

主要核心的代码:

package fun.gosuncn;

import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.xssf.usermodel.*;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.*;

public class Test {

    private static final String url = "jdbc:mysql://gosuncn.fun:3306/gosuncn?serverTimezone=Asia/Shanghai&characterEncoding=utf8";

    private static final String user = "gosuncn";

    private static final String password = "gosuncn";

    private static final String sql = "SELECT `ID`, `NAME`, `COMMENT`, `CREATOR_ID`, `CREATE_TIME` FROM sys_role";

    public static void main(String[] args) {

        /**
         * 创建一个Excel文件对象
         */
        XSSFWorkbook workbook = new XSSFWorkbook();
        /**
         * 创建单元格样式
         */
        XSSFCellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        /**
         * 创建一个表单命名为<角色表>
         */
        XSSFSheet sheet = workbook.createSheet("角色表");
        /**
         * 设置列宽
         */
        sheet.setColumnWidth(0, 10 * 256);
        sheet.setColumnWidth(1, 10 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 15 * 256);
        sheet.setColumnWidth(4, 20 * 256);
        /**
         * 创建第一行
         */
        XSSFRow row = sheet.createRow(0);
        /**
         * 设置每列的标题
         */
        XSSFCell cell = row.createCell(0);
        cell.setCellStyle(style);
        cell.setCellValue("ID");
        cell = row.createCell(1);
        cell.setCellStyle(style);
        cell.setCellValue("NAME");
        cell = row.createCell(2);
        cell.setCellStyle(style);
        cell.setCellValue("COMMENT");
        cell = row.createCell(3);
        cell.setCellStyle(style);
        cell.setCellValue("CREATOR_ID");

        try (Connection connection = DriverManager.getConnection(url, user, password);
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
            ResultSet resultSet = preparedStatement.executeQuery();
            int rowNum = 1;
            while (resultSet.next()) {
                row = sheet.createRow(rowNum);
                int ID = resultSet.getInt("ID");
                String NAME = resultSet.getString("NAME");
                String COMMENT = resultSet.getString("COMMENT");
                int CREATOR_ID = resultSet.getInt("CREATOR_ID");
                Date CREATE_TIME = resultSet.getDate("CREATE_TIME");
                cell = row.createCell(0);
                cell.setCellStyle(style);
                cell.setCellValue(ID);
                cell = row.createCell(1);
                cell.setCellStyle(style);
                cell.setCellValue(NAME);
                cell = row.createCell(2);
                cell.setCellStyle(style);
                cell.setCellValue(COMMENT);
                cell = row.createCell(3);
                cell.setCellStyle(style);
                cell.setCellValue(CREATOR_ID);
                rowNum++;
            }
        } catch (SQLException exception) {
            System.out.println("SQLException Happening ...");
        }

        try (OutputStream outputStream = new FileOutputStream("poi.xlsx")) {
            workbook.write(outputStream);
        } catch (Exception exception) {
            System.out.println("SQLException Happening ...");
        }

    }
}

然后就可以在项目目录下打开poi.xlsx文件了。


http://www.niftyadmin.cn/n/923288.html

相关文章

rabbitmq保证消息投递成功的对比分析

pom.xml 引入rabbitmq所需jar包 <?xml version"1.0" encoding"UTF-8"?> <project xmlns"http://maven.apache.org/POM/4.0.0"xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.…

rabbitmq中confirm和return模式的使用

confirm模式 开启confirm模式channel.confirmSelect(); 这种模式&#xff0c;消息到达交换机时触发&#xff0c;若成功/失败到达交换机时&#xff0c;调用成功/失败回调函数。 import com.rabbitmq.client.*;import java.io.IOException;public class Sender {public static…

设置SELinux的模式

查看SELinux模式 getenforce 设置SELinux setenforce [Enforcing|Permissive|1|0] 配置SELinux [rootgosuncn ~]# cat /etc/selinux/config # This file controls the state of SELinux on the system. # SELINUX can take one of these three values: # enforcing - SELi…

CentOS-7替换Aliyun的yum源

在目录/etc/yum.repos.d下新建一个文件以.repo结尾&#xff0c;比如CentOS-Aliyun.repo。并且填充镜像内容&#xff1a; 使用以下命令即可 cat >/etc/yum.repos.d/CentOS-Aliyun.repo <<EOF [alibase] nameCentOS-7 - Base - mirrors.aliyun.com failovermethodpriori…

ifconfig命令操作网卡

安装ifconfig命令 若系统提示未安装ifconfig软件&#xff0c;可通过以下命令安装&#xff1a; yum -y install net-tools查看网卡信息 [rootmachine01 ~]# ifconfig ens33: flags4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 10.0.0.1 netmask 255.255.255.0…

设置系统光盘开机自动挂载

查看光盘文件 [rootmachine01 ~]# ls /dev/cdrom /dev/cdrom编辑文件/etc/fstab [rootmachine01 ~]# vim /etc/fstab添加最后一行的内容 /dev/cdrom /mnt iso9660 defaults 0 0 /dev/mapper/centos-root / xfs defaults 0 0 UUID32ac6609…

使用postfix和dovecot搭建邮件服务器

创建系统用户 useradd peining1 passwd peining1 # 密码设为 123456 useradd peining2 passwd peining3 # 密码设为 123456安装postfix和dovecot yum install -y postfix yum install -y dovecot配置并启动postfix vim /etc/postfix/main.cfmyhostname mail.gosuncn.fun …

MySQL安装随笔

参考官网 数据库安装文档 [ https://dev.mysql.com/doc/refman/5.7/en/binary-installation.html ] 数据初始化文档 [ https://dev.mysql.com/doc/refman/5.7/en/data-directory-initialization.html ] mysql-5.7.33-linux-glibc2.12-x86_64.tar下载 [ https://dev.mysql.com/g…