导出Excel就这么简单

小菜鸡的学习之路!!!

发现公司项目里有好多地方都用到了导出Excel表格。然后就这两天回家之后简单的学了下,防止下次要用到了急急忙忙的没有头绪.
那首先我们去官网看看吧啦啦啦…
官方API: https://poi.apache.org/.

我们可以跟着API上的例子做一下
我们讲下最重要的几个吧

首先导入依赖

<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>
//创建一个工作蒲对象
Workbook wb = new HSSFWorkbook();  
//创建新表(sheet) 见图1.1
HSSFSheet sheet1 = wb.createSheet("new sheet"); 
//创建行(第0行)
HSSFRow row = sheet.createRow(0);
//创建单元格(第一个单元) 这两行加起来就是 第0行第0个 也可以说第1行一列.看你自己怎么去理解了
HSSFCell cell = row.createCell(0);
//给该单元格设置值
cell.setCellValue("myq最帅啦...");
//给单元格设置样式  我们这里只是设置了边框和边框的颜色
XSSFCellStyle style = wb.createCellStyle(); //创建样式
style.setAlignment(HorizontalAlignment.CENTER); //设置左右水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER); //设置上下垂直居中
style.setBorderBottom(BorderStyle.THIN); //设置border的粗细(细线)
style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); //设置border黑色好像是这样的 我没有仔细去看 效果是实现了 但是这个方法很不人性化
//将style设置进去  没有这一步是不会启用你写好的样式的
cell.setCellStyle(style);

在这里插入图片描述
                                                      图1.1

好了大概了解到这些了我们就可以写出一个像样点的代码了,并且与数据库交互一下 这里我使用到的框架是Springboot + mybatis 大家要是还不会大框架的话可以去看一下 Spring整合Mybatis.

编写Controller

@RestController
public class XSSFController {
    @Autowired
    IUserService userService;

    /**
     * 创建工作蒲对象
     */
    @RequestMapping("/XSSF")
    public void createWorkbook(HttpServletResponse response) {

        {
            try {
                response.setContentType("application/vnd.ms-excel"); //告诉浏览器要保存什么文件
                response.addHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode("公司人员信息.xls", "UTF-8")); //设置下载的名字
                //通过response获取字节输出流
                OutputStream os = response.getOutputStream();
                XSSFWorkbook wb = new XSSFWorkbook();
                XSSFCellStyle style = wb.createCellStyle();
                //设置边框样式及颜色
                style.setAlignment(HorizontalAlignment.CENTER);
                style.setVerticalAlignment(VerticalAlignment.CENTER);
                style.setBorderBottom(BorderStyle.THIN);
                style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
                style.setBorderLeft(BorderStyle.THIN);
                style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
                style.setBorderTop(BorderStyle.THIN);
                style.setTopBorderColor(IndexedColors.BLACK.getIndex());
                style.setBorderRight(BorderStyle.THIN);
                style.setRightBorderColor(IndexedColors.BLACK.getIndex());
                XSSFSheet sheet1 = wb.createSheet("sheet");
                XSSFRow titleRow = sheet1.createRow(0);
                titleRow.createCell(0).setCellValue("编号");
                titleRow.createCell(1).setCellValue("名称");
                titleRow.createCell(2).setCellValue("年龄");
                titleRow.createCell(3).setCellValue("性别");
                titleRow.createCell(4).setCellValue("状态");
                List<User> userList = userService.allQuery();
                int rowIndex = 1;
                for (User user:userList){
                    XSSFRow row = sheet1.createRow(rowIndex);
                    String[] strings = user.toString().split(",");  //注意这里重写了用户实体类的toString方法,写法有严格要求
                    int cellIndex = 0;
                    while (cellIndex < strings.length){     //循环字符串数组长度的次数
                        XSSFCell cell = row.createCell(cellIndex);
                        cell.setCellValue(strings[cellIndex]);
                        cellIndex++;
                        cell.setCellStyle(style);
                    }
                    rowIndex++;
                }
                sheet1.addMergedRegion(new CellRangeAddress( //合并最后的日期单元格
                        rowIndex,
                        rowIndex,
                        0,
                        4
                ));
                XSSFRow rowEnd = sheet1.createRow(rowIndex);
                XSSFCell cell = rowEnd.createCell(0);
                cell.setCellValue("yyyy-mm-dd");
                cell.setCellStyle(style);
                wb.write(os);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

主要就是Controller的代码,这里在处理怎么能够循环创建并且填充cell的时候真的是花了我好久,我们这里是用的split,将对象转成了字符串数组再添加进去的

实体类

package com.mjw.pojo;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String name;
    private String age;
    private String sex;
    private String status;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    @Override
    public String toString() {
        return id +
                "," + name + '\'' +
                "," + age + '\'' +
                "," + sex + '\'' +
                "," + status;
    }
}

实体类重写toString的时候必须按照此规则进行重写,不然split的时候就有问题,得到的数据是不能进行set进cell的.
service层、dao层和mapper我就不贴出来了就是简单的查询所有数据

HTML及JS
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../js/jquery.min.js"></script>
    <style>
        #exportExcel{
            margin-left: 70%;
        }
    </style>
</head>
<body>
<button id="exportExcel" >excel</button>
<input type="number" value="lalala">
</body>
<script>
    $(function () {
        $("#exportExcel").click(function () {
            window.location.href = "/XSSF";
        })
    })
</script>
</html>

来看一下我们导出的Excel如何

在这里插入图片描述

成功!!!

结果好丑啊… 果然自己写的就是丑,如果大家要那种效果好看的可以去网上找找大佬们写好的工具包,封装类. 如果有需要的花我过段时间可以更新个实际开发中用到的Excel 看看大佬们是怎么用的

发布了5 篇原创文章 · 获赞 5 · 访问量 329

猜你喜欢

转载自blog.csdn.net/weixin_45310564/article/details/105567624