Springboot整合poi +vue实现导出导入Excle表格数据展示图形

工具: idea

数据库: mysql

框架:Springboot

准备工作:

1.导入主要依赖 (poi)


            org.apache.poi
            poi
            4.1.2
        
        
            org.apache.poi
            poi-excelant
            4.1.2
        
        
            org.apache.poi
            poi-ooxml
            4.1.2
        
        
            org.apache.poi
            poi-ooxml-schemas
            4.1.2
        
        
            org.apache.poi
            poi-scratchpad
            4.1.2
        

2.配置yml

server:
  port: 8081

#管理数据源
spring:
  datasource:
    #高版本驱动使用
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/news?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
    #设定用户名和密码
    username: root
    password: root

  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

  thymeleaf:
    prefix: classpath:/templates/ #th模板运行路径
    suffix: .html
    mode: HTML5
    encoding: UTF-8
    cache: false

    resources:
      chain:
        strategy:
          content:
            enabled: true
            paths: /**
      static-locations: classpath:/templates/ #页面运行路径

mybatis:
  mapper-locations: classpath:/mapper/*.xml
  type-aliases-package: com.ketai.springbootpoiechart.pojo



一、数据库导出Excle表格

1.0 实体类

package com.ketai.springbootpoiechart.pojo;

import lombok.*;

import javax.persistence.Column;

@Data
public class Type{

    @Column(name = "id")
    private String id;

    private String tyname;

    public Type(String id, String tyname) {
        this.id = id;
        this.tyname = tyname;
    }

}

1.1 工具类

package com.ketai.springbootpoiechart.util;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class ExportExcel {
    // 导出表的标题
    private String title;
    // 导出表的列名
    private String[] rowName;
    // 导出表的数据
    private List dataList = new ArrayList();

    // 构造函数,传入要导出的数据
    public ExportExcel(String title, String[] rowName, List dataList) {
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
    }

    // 导出数据
    public void export(OutputStream out) throws Exception {
        try {
            //1.创建一个workbook,一个workbook 对应一个Excel文件
            HSSFWorkbook workbook = new HSSFWorkbook();
            //2.创建 sheet excel中多个sheet组成一个excel文件 至少有一个sheet
            HSSFSheet sheet = workbook.createSheet(title);

            //3.在sheet中添加表头第0行
            HSSFRow rowm = sheet.createRow(0);
            //4.创建单元格
            HSSFCell cellTitle = rowm.createCell(0);

            //5.定义标题样式 和 数据样式
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);
            HSSFCellStyle style = this.getStyle(workbook);
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
            cellTitle.setCellStyle(columnTopStyle);
            //6.给单元格设置值
            cellTitle.setCellValue(title);

            //7.获取列标长度
            int columnNum = rowName.length;
            // 创建列 相当于一行 2代表第三行 因为上面的总标题占了两行为 0 1
            HSSFRow rowRowName = sheet.createRow(2);

            //8.将列标题设置到单元格中
            for (int n = 0; n < columnNum; n++) {
                HSSFCell cellRowName = rowRowName.createCell(n);
                cellRowName.setCellType(CellType.STRING);
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);
                cellRowName.setCellStyle(style);
            }

            //9.将数据设置到单元格中
            for (int i = 0; i < dataList.size(); i++) {
                Object[] obj = dataList.get(i);
                HSSFRow row = sheet.createRow(i + 3);
                for (int j = 0; j < obj.length; j++) {
                    HSSFCell cell = null;
                    cell = row.createCell(j, CellType.STRING);
                    if (!"".equals(obj[j]) && obj[j] != null) {
                        cell.setCellValue(obj[j].toString());
                    } else {
                        cell.setCellValue(" ");
                    }
                    cell.setCellStyle(style);
                }
            }


            if (workbook != null) {
                try {
                    //10.将整个表格写出
                    workbook.write(out);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) { }
    }

    /**
     * 表格标题样式
     */
    public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 设置字体颜色
        font.setColor(IndexedColors.WHITE.getIndex());
        // 字体加粗
        font.setBold(true);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置标题背景色
        style.setFillForegroundColor(IndexedColors.DARK_TEAL.getIndex());
        // 设置背景颜色填充样式
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        // 设置低边框
        style.setBorderBottom(BorderStyle.THIN);
        // 设置低边框颜色
        style.setBottomBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 设置右边框
        style.setBorderRight(BorderStyle.THIN);
        // 设置顶边框
        style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 设置顶边框颜色
        style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 在样式中应用设置的字体
        style.setFont(font);
        // 设置自动换行
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 表格数据样式
     */
    public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 10);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(IndexedColors.ROYAL_BLUE.getIndex());
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }
}

1.3 service层

package com.ketai.springbootpoiechart.service;

import java.io.IOException;
import java.io.OutputStream;

public interface ReportService {
    void exportTest(OutputStream out, String excelTitle) throws IOException;
}

1.4 实现impl

package com.ketai.springbootpoiechart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ketai.springbootpoiechart.mapper.ReportMapper;
import com.ketai.springbootpoiechart.pojo.Type;
import com.ketai.springbootpoiechart.service.ReportService;
import com.ketai.springbootpoiechart.util.ExportExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    ReportMapper reportMapper;

    @Override
    public void exportTest(OutputStream out, String excelTitle) throws IOException {
        // 定义列标 就是一个Excel的标题而已 下面有图介绍
        String[] rowsName = new String[]{"新闻编号", "新闻标题"};
        // 创建导出数据集合 后续会将dataList中的数据写到Excel
        List dataList = new ArrayList();
        // 从数据库查询用户列表
        QueryWrapper queryWrapper = new QueryWrapper();
        List userList = reportMapper.selectList(queryWrapper);
        Type type = null;
        // 将用户列表信息封装到一个Object数组
        // 我这里封装Object数组 是为了方便后续代码复用,不会将对象类型写死
        // 当然也可以在下一层使用反射来做,太麻烦了 还是这样转一下吧
        for (int i=0;i

1.5 编写Controller

 //导出
    @Autowired
    ReportService reportService;

    @GetMapping("/reportExport/prodTest")
    public Object prodTest(HttpServletResponse response, String excelTitle) throws IOException {
        // 创建导出文件名称 当前日期+前台传递过来的标题名(excelTitle)
        String fileName = DateUtils.format(new Date(),"yyyyMMddHHmmss") +"-"+excelTitle+".xls";
        // 设置返回的消息头和返回值类型 并设置编码 不设置编码文件名为中文的话 不会显示
        // 当设置成如下返回值时,浏览器才会执行下载文件动作
        response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
        response.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");
        // 创建输出流,调用service中exportTest方法,参数:输出流 标题名
        reportService.exportTest(response.getOutputStream(), excelTitle);
        return null;
    }

这样就可以生成excle表格了

———————————————————————————————————————————

二、导入Excle表格

2.1 实体类

package com.ketai.springbootpoiechart.pojo;

import lombok.*;

import javax.persistence.Column;

@Data
public class Type{

    @Column(name = "id")
    private String id;

    private String tyname;

    public Type(String id, String tyname) {
        this.id = id;
        this.tyname = tyname;
    }

}

2.2 service层

package com.ketai.springbootpoiechart.service;

import com.ketai.springbootpoiechart.mapper.TypeMapper;
import com.ketai.springbootpoiechart.pojo.Type;
import jxl.Sheet;
import jxl.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class TypeService {
    @Autowired
    private TypeMapper typeMapper;

    /**
     * 查询指定目录中电子表格中所有的数据
     *
     * @param file 文件完整路径
     * @return
     */
    public Integer getAllByExcel(String file) {
        List list = new ArrayList();
        try {
            Workbook rwb = Workbook.getWorkbook(new File(file));
            Sheet rs = rwb.getSheet(0);//或者rwb.getSheet(0)
            int clos = rs.getColumns();//得到所有的列
            int rows = rs.getRows();//得到所有的行

            System.out.println(clos + " rows:" + rows);
            for (int i = 1; i < rows; i++) {
                for (int j = 0; j < clos; j++) {
                    //第一个是列数,第二个是行数
                    String id = rs.getCell(j++, i).getContents();//默认最左边编号也算一列 所以这里得j++
                    String tyname = rs.getCell(j++, i).getContents();

                    System.out.println("id:" + id + " tyname:" + tyname);
                    list.add(new Type(id,tyname));
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return typeMapper.insert(list);

    }

}

2.3 Mapper

package com.ketai.springbootpoiechart.mapper;

import com.ketai.springbootpoiechart.pojo.Type;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface TypeMapper {
    Integer insert(List list);

}

2.4 Mapper.xml

 
        insert into `type`(id,tyname) values
        
            (#{item.id},#{item.tyname})
        
    

2.5 编写Controller

//导入
    @Autowired
    private TypeService typeService;

    @GetMapping("/Excel")
    @ResponseBody
    public String insertCarByExcel(String file) {
       // String file = "E:\\Users\\1205\\Downloads\\20221128130548-新闻编号.xls";
        //ModelAndView modelAndView = new ModelAndView("complete");
        Integer integer = typeService.getAllByExcel(file);
        if (integer > 0) {
            System.out.println("导入成功");
            return "成功";
        }else{
            return "失败";
        }
    }

三、前端页面

(),这里  导入 时需要配置浏览器的安全设置,不然浏览器会给一个默认的路径,











这样就可以导入Excle表格了

——————————————————————————————————————————

三、数据展示

3.1 安装axios

npm install axios

3.2 3.部署axios环境

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

在main.js中引入

4.遍历数据











5 效果展示 饼状图及柱状图

Springboot整合poi +vue实现导出导入Excle表格数据展示图形_第1张图片

 

你可能感兴趣的:(vue.js,spring,boot,前端)