SpringBoot+thymeleaf模板引擎实现Excel表格的导入导出

一:环境

//父工程项目依赖2.7.14  jdk版本1.8
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.14</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

1.导入依赖 

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

用于操作Microsoft Office文档
<!-- Apache POI dependencies -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version> <!-- 使用时请检查最新版本 -->
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version> <!-- 使用时请检查最新版本 -->
</dependency>
用于读取、写入和操作Excel文件(特别是较旧的.xls格式)
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
    <groupId>net.sourceforge.jexcelapi</groupId>
    <artifactId>jxl</artifactId>
    <version>2.6.12</version>
</dependency>

2.前端页面

前端代码:

//使用form表单发送post请求   style="display: none"(隐藏form表单)
<button onclick="uploadExcel.click()">导入</button>
<form th:action="@{/insertExcel}" method="post" style="display: none" enctype="multipart/form-data">
    <input type="file" id="uploadExcel" name="file" value="表格上传" onchange="changepic(this)" />
    <input type="submit" id="clickButton" class="btn btn-primary">上传文件</input>
</form>
<script>
    function changepic(input) {
        var file = input.value;
        if(file != null){
            document.getElementById("clickButton").click();
        }
    }
</script>
<button onclick="clickButton1.click()">导出</button>
<form th:action="@{/exportCarByExcel}" method="post" style="display: none" >
    <button type="submit" id="clickButton1" class="btn btn-primary"></button>
</form>

二:后端代码:

1.实体类(Student)

@Data
public class User {
  private Integer id;
  private String userName;
  private String password;
  private String nickName;
  private String phone;
  private String email;
  private long roleId;
}

2.Controller

/**
 * 导入excel表格
 */
@PostMapping("/insertExcel")
public String insertStudent(@RequestParam("file") MultipartFile file) throws IOException {
    UploadImageController uploadImageController = new UploadImageController();
    String upload = uploadImageController.uploadExcel(file);
    insertExecel insertExecel = new insertExecel();
    List<Student> studentList = insertExecel.readExcel(0,upload);
    int i = studentService.insertStudent(studentList);
    return "redirect:/selectStudentList";
}
/**
 * 导出文件表格
 */
@PostMapping("/exportStudentByExcel")
public void exportCarByExcel(HttpServletResponse response) throws IOException {
    //调用工具类中的导出表格的方法
    insertExecel  = new insertExecel();
    List<Student> list = studentService.getStudentList();
    //将从数据库中查询到的list集合传入exportExcel方法中
    String excelPath = insertExecel.exportExcel(list);
    excelPath = "\\excel" + excelPath;
    //返回生成excel文件的路径   浏览器下载excel表格
    insertExecel.fileDownload(excelPath,response);
}

3.工具类(insertExecel)

导入的excel文件后缀需为(.xls) 导出的文件格式后缀也为(.xls)

public class insertExecel {
    /**
     * 导入表格
     * @param sheetIndex(sheetIndex 就是用来标识这个特定工作表的)
     * @param filePath (前端传入的文件的名字)
     * @return
     * @throws IOException
     */
    public List<Student> readExcel( int sheetIndex,String filePath) throws IOException {
        
        List<Student> dataList = new ArrayList<>();
        
        File file = new File(filePath);
        
        FileInputStream fis = new FileInputStream(file);

        HSSFWorkbook workbook = null;
        workbook = new HSSFWorkbook(fis);
        if (workbook != null) {
            Sheet sheet = workbook.getSheetAt(sheetIndex);
            for (Row row : sheet) {
                if (row.getRowNum() == 0) {
                    // 如果是标题行,可以跳过或者处理标题
                    continue;
                }
                Student data = new Student();
                for (Cell cell : row) {
                    switch (cell.getCellType()) {
                        case STRING:
                            if(cell.getColumnIndex() == 0){
                                data.setId((Integer.parseInt(cell.getStringCellValue()+"")));
                            }
                            // 假设第一列存储到cell1,第二列存储到cell2等
                            else if (cell.getColumnIndex() == 1) {
                                data.setName(cell.getStringCellValue());
                            }
                            else if (cell.getColumnIndex() == 2) {
                                data.setSex(cell.getStringCellValue());
                            }
                            else if (cell.getColumnIndex() == 3) {
                                data.setAge(Integer.parseInt(cell.getStringCellValue()+""));
                            }
                            else if (cell.getColumnIndex() == 4) {
                                data.setPhone(cell.getStringCellValue());
                            }
                            else if (cell.getColumnIndex() == 5) {
                                data.setEmail(cell.getStringCellValue());
                            }
                            else if (cell.getColumnIndex() == 6) {
                                data.setScore(Double.valueOf(cell.getStringCellValue()+""));
                            }
                            else if (cell.getColumnIndex() == 7) {
                                data.setClassId(Integer.parseInt(cell.getStringCellValue()+""));
                            }
                            else if (cell.getColumnIndex() == 8) {
                                data.setPhoto(cell.getStringCellValue());
                            }
                            else if (cell.getColumnIndex() == 9) {
                                data.setMoreImage(cell.getStringCellValue());
                            }
                            break;
                        // 处理其他类型的单元格,如NUMERIC, BOOLEAN, FORMULA等
                    }
                }
                dataList.add(data);
            }
            workbook.close();
        }
        fis.close();
        return dataList;
    }
    //这是我项目的excel存放文件夹的根路径 需要更换成自己的路径
    String fileName = "D:\\IDEA2022.3\\SpringBoot\\springboot-02\\src\\main\\resources\\static\\upload\\excel";
    public String exportExcel(List list) {

        try {
            WritableWorkbook wwb = null;
            // 创建可写入的Excel工作簿
            SimpleDateFormat sdf = new SimpleDateFormat("yyMMddHHmmss");
            String dname = sdf.format(new Date());

            fileName = fileName + "\\" + dname + "-student.xls";
            File file=new File(fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
            //以fileName为文件名来创建一个Workbook
            wwb = Workbook.createWorkbook(file);

            // 创建工作表
            WritableSheet ws = wwb.createSheet("Test Shee 1", 0);

            //要插入到的Excel表格的行号,默认从0开始
            Label labelId = new Label(0, 0, "编号(id)");//表示第
            Label labelName = new Label(1, 0, "姓名(name)");
            Label labelSex = new Label(2, 0, "性别(sex)");
            Label labelAge = new Label(3, 0, "年龄(age)");
            Label labelPhone = new Label(4, 0, "手机号(phone)");
            Label labelEmail = new Label(5, 0, "邮箱(email)");
            Label labelScore = new Label(6, 0, "分数(score)");
            Label labelClassId = new Label(7, 0, "班级(classId)");
            Label labelPhoto = new Label(8, 0, "头像(photo)");
            Label labelMoreImage = new Label(9, 0, "生活照(moreImage)");

            ws.addCell(labelId);
            ws.addCell(labelName);
            ws.addCell(labelSex);
            ws.addCell(labelAge);
            ws.addCell(labelPhone);
            ws.addCell(labelEmail);
            ws.addCell(labelScore);
            ws.addCell(labelClassId);
            ws.addCell(labelPhoto);
            ws.addCell(labelMoreImage);

            List<Student> studentList = list;

            for (int i = 0; i < studentList.size(); i++) {

                Label labelId_i = new Label(0, i + 1, studentList.get(i).getId() + "");
                Label labelName_i = new Label(1, i + 1, studentList.get(i).getName());
                Label labelSex_i = new Label(2, i + 1, studentList.get(i).getSex());
                Label labelAge_i = new Label(3, i + 1, studentList.get(i).getAge() + "");
                Label labelPhone_i = new Label(4, i + 1, studentList.get(i).getPhone());
                Label labelEmail_i = new Label(5, i + 1, studentList.get(i).getEmail());
                Label labelScore_i = new Label(6, i + 1, studentList.get(i).getScore() + "");
                Label labelClassId_i = new Label(7, i + 1, studentList.get(i).getClassgrade().getId()+"");
                Label labelPhoto_i = new Label(8, i + 1, studentList.get(i).getPhoto());
                Label labelMoreImage_i = new Label(9, i + 1, studentList.get(i).getMoreImage());

                ws.addCell(labelId_i);
                ws.addCell(labelName_i);
                ws.addCell(labelSex_i);
                ws.addCell(labelAge_i);
                ws.addCell(labelPhone_i);
                ws.addCell(labelEmail_i);
                ws.addCell(labelScore_i);
                ws.addCell(labelClassId_i);
                ws.addCell(labelPhoto_i);
                ws.addCell(labelMoreImage_i);
            }

            //写进文档
            wwb.write();
            // 关闭Excel工作簿对象
            System.out.println("表格数据导出成功!");
            wwb.close();
            return  "\\" + dname + "-student.xls";

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }

    private String Path = "D:\\IDEA2022.3\\SpringBoot\\springboot-02\\src\\main\\resources\\static\\upload";
    //文件下载
    public void fileDownload(String filePath, HttpServletResponse response) throws IOException {
        // 创建输入流,读取文件
        FileInputStream fis = new FileInputStream(Path + "\\" + filePath);
        // 设置响应头信息
        response.setHeader("Content-Disposition", "attachement;filename=" +
                filePath.substring(filePath.lastIndexOf("/") + 1));
        // 获取输出流
        ServletOutputStream out = response.getOutputStream();
        // 拷贝
        IOUtils.copy(fis, out);
    }
}

4.Mapper(sql语句循环遍历添加) 

<insert id="insertStudent">
    insert into student
    values
    <foreach collection="list" separator="," item="item">
        (null,#{item.name},#{item.sex},#{item.age},#{item.phone},#{item.email},
         #{item.score},#{item.classId},#{item.photo},#{item.moreImage})
    </foreach>
</insert>

三:效果展示

  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
书城管理系统主要分为前台和后台两部分,前台主要是面向读者的,包括图书展示、购买、借阅等功能;后台主要是面向管理员的,包括图书管理、用户管理、订单管理等功能。 下面是一个基于SpringBoot + Thymeleaf + Mybatis的书城管理系统的简单实现: 1. 数据库设计 - 用户表:id, username, password, email, phone - 图书表:id, book_name, author, price, stock, sales, image - 订单表:id, user_id, book_id, status, create_time, update_time 2. 实体类设计 - 用户类:包括id、用户名、密码、邮箱、电话等属性 - 图书类:包括id、书名、作者、价格、库存、销量、图片等属性 - 订单类:包括id、用户id、图书id、状态、创建时间、更新时间等属性 3. DAO层设计 - 用户DAO:包括增删改查等操作,使用Mybatis注解或XML方式实现 - 图书DAO:包括增删改查等操作,使用Mybatis注解或XML方式实现 - 订单DAO:包括增删改查等操作,使用Mybatis注解或XML方式实现 4. 服务层设计 - 用户服务:包括用户注册、登录、修改密码、查询用户信息等方法 - 图书服务:包括图书查询、购买、借阅、归还等方法 - 订单服务:包括订单生成、查询、修改状态等方法 5. 控制层设计 - 前台控制器:包括图书展示、购买、借阅等操作的处理 - 后台控制器:包括图书管理、用户管理、订单管理等操作的处理 6. 视图层设计 - 前台视图:包括图书展示、购买、借阅等页面的设计 - 后台视图:包括图书管理、用户管理、订单管理等页面的设计 以上是一个简单的基于SpringBoot + Thymeleaf + Mybatis的书城管理系统的设计实现,可以根据实际需求进行调整和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eternal-xin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值