JAVA导出MySQL数据库数据生成Excel表

环境:JDK1.8、Maven3.6.3、Mysql8.0、poi4.1、Mybatis-plus3.4.3
话不多说,先上代码。后续需要自己整理一下分层,保持代码的干净整洁从自己做起。
Controller:如下`

package com.example.testexcel.controller;

import com.example.testexcel.dao.userDao;
import com.example.testexcel.entity.client;
import com.example.testexcel.util.ResponseUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;

/**
 * Author: 于顺清
 * Coopyright(C),2019-2022
 * FileName:excelController
 * Date:     2022/1/7/00714:28
 * Description:表的导出
 */
@RestController
public class excelController {
    @Autowired
    userDao userdao;
    @RequestMapping("excel_down")
    public String Excel_Down(HttpServletResponse response){

        String table_url = this.getClass().getClassLoader().
                getResource("static/webapp/client_table.xls").getPath();
//        System.out.println(table_url);
        List<client> list = userdao.selectList(null);
        Workbook workbook = fillExcelDataWithTemplate(list,table_url);
        try {
            ResponseUtil.export(response,workbook,"客户表.xlsx");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功";
    }

    private Workbook fillExcelDataWithTemplate(List<client> list, String templateUrl) {

        Workbook wb = null;
        try {
            POIFSFileSystem fileSystem = new POIFSFileSystem(new FileInputStream(templateUrl));
            wb = new HSSFWorkbook(fileSystem);
            //wb = new XSSFWorkbook(String.valueOf(fileSystem));
            //取得模板的第一个首页
            Sheet sheet = wb.getSheetAt(0);
           //拿到sheet有多少列
            //int cellNums = sheet.getRow(0).getLastCellNum();
           //从第二行开始,下标是1
            int rowIndex = 1;
            Row row;
            for(client c : list){
                row = sheet.createRow(rowIndex);
                rowIndex++;
                row.createCell(0).setCellValue(c.getId());
                row.createCell(1).setCellValue(c.getNumber());
                row.createCell(2).setCellValue(c.getUsername());
                row.createCell(3).setCellValue(c.getPhone());
                row.createCell(4).setCellValue(c.getNote());
                row.createCell(5).setCellValue(DateFormatUtils.format(c.getCreattime(),"yyyy-MM-dd HH:mm:ss"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
}

DAO:

package com.example.testexcel.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.testexcel.entity.client;
import org.apache.ibatis.annotations.Mapper;

/**
 * Author: 于顺清
 * Coopyright(C),2019-2022
 * FileName:userDao
 * Date:     2022/1/8/00813:26
 * Description:用于Excel导入导出数据
 */
@Mapper
public interface userDao extends BaseMapper<client> {

}

entity:

package com.example.testexcel.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;

/**
 * Author: 于顺清
 * Coopyright(C),2019-2022
 * FileName:client
 * Date:     2022/1/7/00715:11
 * Description:客户信息类
 */
@Data
@TableName(value = "sys_excel_test")
public class client {

    private Integer id;
    //@ExcelColumn(value="编号",col = 2)
    private String number;
    private String username;
    private String phone;
    private String note;
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date creattime;

}

util:

package com.example.testexcel.util;

 import java.io.OutputStream;
 import java.io.PrintWriter;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.poi.ss.usermodel.Workbook;
 public class ResponseUtil {
        public static void write(HttpServletResponse response,Object o) throws Exception{
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println(o.toString());
        out.flush();
        out.close();
}

public static void export(HttpServletResponse response,Workbook wb,String fileName)throws Exception{
        response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("utf-8"),"iso8859-1"));
        response.setContentType("application/ynd.ms-excel;charset=UTF-8");
        OutputStream out=response.getOutputStream();
        wb.write(out);
        out.flush();
        out.close();
        }
}

Pom:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>testexcel</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>testexcel</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--excel导入导出-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml-schemas</artifactId>
            <version>4.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
        <!-- 阿里数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- lombok工具 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!--mybatis-plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.3.4</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>

    </build>

</project>

到这里为止直接启动Application即可。在浏览器里面访问http://localhost:8080/excel_down这个地址就可以下载出来了。
在这里插入图片描述
不过有个小问题,如果我们在实际应用中出现一种情况–即客户想使用自己上传的模板进行导出数据呢。
这里要注意一个点,就是客户传进来的模板表是xls还是xlsx,一个代表2003一个代表2007版,这里容易出现一个问题,就是版本问题无法识别。错误如下:
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied data appears to be in the Office 2007+ XML. You are calling the part of POI that deals with OLE2 Office Documents. You need to call a different part of POI to process this data (eg XSSF instead of HSSF)
我在CSDN上找到一个觉得挺有帮助的一段话。
在这里插入图片描述
所以我们在做这个功能的时候,应该先加一个判断判断所选择的模板是什么类型,再决定调用哪个方法。
以下是使用xlsx模板的代码(和上面代码是同一个项目结构,放在一起的)。没有和上面整合,下面是在代码里面直接写死了下载的位置,执行即直接下载到该位置。可以自己改成自己的位置。一般写桌面位置。
util包下Xlsx类:

package com.example.testexcel.util;

/**
 * Author: 于顺清
 * Coopyright(C),2019-2022
 * FileName:Xlsx
 * Date:     2022/1/11/01118:37
 * Description:yu1
 */
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Xlsx {
//标题,内容,下表名
public XSSFWorkbook getWorkBook(List<String> titleList, List<List<String>> contentlist, String sheetName) {
    XSSFWorkbook xwk = new XSSFWorkbook();
    XSSFDataFormat format = xwk.createDataFormat();
    XSSFCellStyle cellStyle = xwk.createCellStyle();
    XSSFSheet xssfSheet = xwk.createSheet(sheetName);
    cellStyle.setDataFormat(format.getFormat("@"));//文本格式             
    int j = 0;
    createHeader(xssfSheet, cellStyle, titleList, j);
    int size = contentlist.size();
    for (j = 0; j < size; j++) {
        List<String> oneRow = contentlist.get(j);
        createContent(xssfSheet, cellStyle, oneRow, j);
        oneRow = null;
    }
    return xwk;
}
private void createHeader(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> titleList, int j) {

    XSSFRow rowTitle = xssfSheet.createRow(j);
    for (int cellTitle = 0; cellTitle < titleList.size(); cellTitle++) {
        Cell cellIndex = rowTitle.createCell(cellTitle);
        cellIndex.setCellStyle(cellStyle);
        cellIndex.setCellValue(titleList.get(cellTitle));
    }
}
private void createContent(XSSFSheet xssfSheet, XSSFCellStyle cellStyle, List<String> oneRow, int j) {
    XSSFRow rowContent = xssfSheet.createRow(j + 1);
    for (int cellContent = 0; cellContent < oneRow.size(); cellContent++) {
        Cell cellIndex = rowContent.createCell(cellContent);
        cellIndex.setCellStyle(cellStyle);
        cellIndex.setCellValue(oneRow.get(cellContent));
    }
  }
}

测试类:

package com.example.testexcel;

import com.example.testexcel.util.Xlsx;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileNotFoundException;
import java.util.List;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@SpringBootTest
class TestexcelApplicationTests {

    @Test
    void contextLoads() throws IOException {
        List<String> titleList = new  ArrayList<String>();
        titleList.add("NO");
        titleList.add("ID");
        titleList.add("Name");
        titleList.add("Age");
        List<String> content = null;
        List<List<String>> contentsList = new  ArrayList<List<String>>();
        content = new ArrayList<String>();
        content.add("1");
        content.add("180001");
        content.add("Jame");
        content.add("18");
        contentsList.add(content);
        content = new ArrayList<String>();
        content.add("1");
        content.add("180002");
        content.add("Lucky");
        content.add("18");
        contentsList.add(content);

        XSSFWorkbook workBook = null;
        FileOutputStream output = null;
        String sheetName = "student";
        String fileName = "D:/student.xlsx";

        if (contentsList.size() > 0) {
            try {
                Xlsx eu = new Xlsx();
                workBook = eu.getWorkBook(titleList, contentsList, sheetName);
                output =  new FileOutputStream(fileName);
                workBook.write(output);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if(output != null){
                    output.flush();
                    output.close();
                }
                if (workBook != null) {
                    workBook.close();
                }
            }
        }
    }
}

判断的话,之前看到过一个好的判断,没找到了,是直接判断表类型的。
先用着下面这个叭。
//获得文件名 String fileName =file.getOriginalFilename();
//判断文件是否是excel文件 if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx))

  • 8
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您可以使用Java的JDBC API和Apache POI库来将数据库信息导出Excel格。下面是一个简单的示例代码,可以将MySQL数据库信息导出Excel格: ```java import java.sql.*; import java.io.*; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.*; public class ExportTableToExcel { public static void main(String[] args) throws Exception { // 连接到MySQL数据库 String url = "jdbc:mysql://localhost:3306/test"; String user = "root"; String password = "123456"; Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection(url, user, password); // 查询信息 String sql = "SHOW TABLES"; PreparedStatement stmt = conn.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); // 创建Excel格 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Table Info"); // 添加头 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Table Name"); headerRow.createCell(1).setCellValue("Number of Columns"); // 添加信息 int rowNum = 1; while (rs.next()) { String tableName = rs.getString(1); sql = "SELECT COUNT(*) FROM information_schema.columns WHERE table_name = ?"; stmt = conn.prepareStatement(sql); stmt.setString(1, tableName); ResultSet rs2 = stmt.executeQuery(); rs2.next(); int numColumns = rs2.getInt(1); Row row = sheet.createRow(rowNum++); row.createCell(0).setCellValue(tableName); row.createCell(1).setCellValue(numColumns); } // 输出Excel格 FileOutputStream outputStream = new FileOutputStream("table_info.xlsx"); workbook.write(outputStream); workbook.close(); // 关闭连接 rs.close(); stmt.close(); conn.close(); } } ``` 该代码使用了Apache POI库来创建Excel格,并使用JDBC API从MySQL数据库查询信息。您可以根据需要修改该代码以适应不同的数据库导出要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值