Springboot+poi+实现导出导入Excle表格+Vue引入echarts数据展示

需求: 一. 数据库数据表导出Excle表格

          二. Excle数据导入数据库

          三. Vue引入Echarts数据展示

工具: idea

数据库: mysql

框架:Springboot

准备工作:

1.maven主要依赖:poi

   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

2.yaml配置

spring:
  thymeleaf:
    cache: false
    suffix=: .html
    prefix: classpath:/templates/
  datasource:
    url: jdbc:mysql://localhost:3306/mylove?serverTimezone=GMT-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
mybatis-plus:
#  mapperLocations: classpath:mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 全局配置id自增  =>
  global-config:
    db-config:
      id-type: auto

一. 数据库数据表导出Excle表格

1.准备实体类(我这个是两表联查的实体类,有需要的可以单表)

 2.service查询数据

 两表查询出数据List集合

3.准备Excle工具类

public class ExcelUtil {

    /**
     * Excel表格导出
     * @param response HttpServletResponse对象
     * @param excelData Excel表格的数据,封装为List<List<String>>
     * @param sheetName sheet的名字
     * @param fileName 导出Excel的文件名
     * @param columnWidth Excel表格的宽度,建议为15
     * @throws IOException 抛IO异常
     */
    public static void exportExcel(HttpServletResponse response,
                                   List<List<String>> excelData,
                                   String sheetName,
                                   String fileName,
                                   int columnWidth) throws IOException {

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格,设置表格名称
        HSSFSheet sheet = workbook.createSheet(sheetName);

        //设置表格列宽度
        sheet.setDefaultColumnWidth(columnWidth);

        //写入List<List<String>>中的数据
        int rowIndex = 0;
        for(List<String> data : excelData){
            //创建一个row行,然后自增1
            HSSFRow row = sheet.createRow(rowIndex++);

            //遍历添加本行数据
            for (int i = 0; i < data.size(); i++) {
                //创建一个单元格
                HSSFCell cell = row.createCell(i);

                //创建一个内容对象
                HSSFRichTextString text = new HSSFRichTextString(data.get(i));

                //将内容对象的文字内容写入到单元格中
                cell.setCellValue(text);
            }
        }

        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        //刷新缓冲
        response.flushBuffer();

        //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
        workbook.write(response.getOutputStream());

        //关闭workbook
        workbook.close();
    }

}

4.编写Controller接口

@Controller
public class ExcelController {
    @Autowired
    goodServiceImpl goodService;

    /**
     * Excel表格导出接口
     * http://localhost:8080/ExcelDownload
     *
     * @param response response对象
     * @throws IOException 抛IO异常
     */
    @RequestMapping("/ExcelDownload")
    public void excelDownload(HttpServletResponse response) throws IOException {
        //表头数据
        String[] header = {"id", "数量", "姓名", "单价", "物品类型"};

        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();

        //生成一个表格,设置表格名称为"学生表"
        HSSFSheet sheet = workbook.createSheet("学生表");

        //设置表格列宽度为10个字节
        sheet.setDefaultColumnWidth(10);

        //创建第一行表头
        HSSFRow headrow = sheet.createRow(0);

        //遍历添加表头(下面模拟遍历学生,也是同样的操作过程)
        for (int i = 0; i < header.length; i++) {
            //创建一个单元格
            HSSFCell cell = headrow.createCell(i);

            //创建一个内容对象
            HSSFRichTextString text = new HSSFRichTextString(header[i]);

            //将内容对象的文字内容写入到单元格中
            cell.setCellValue(text);
        }


      //***********************************
        //拿到数据
        List<Goods> goods = goodService.findAllGoods();
        for (int i = 0; i < goods.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            Goods good = goods.get(i);
            HSSFCell cell = null;
            String[] names = {Math.toIntExact(good.getId()) + "",
                    good.getCount() + "",
                    good.getName() + "",
                    good.getPrice() + "",
                    good.getType() + ""};
            for (int k = 0; k < names.length; k++) {
                cell = row.createCell(k);
                //拿到属性值
                HSSFRichTextString text = new HSSFRichTextString(names[k]);
                cell.setCellValue(text);
            }
        }
        //*****************************************


        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");

        //这后面可以设置导出Excel的名称,此例中名为student.xls
        response.setHeader("Content-disposition", "attachment;filename=student.xls");

        //刷新缓冲
        response.flushBuffer();

        //workbook将Excel写入到response的输出流中,供页面下载
        workbook.write(response.getOutputStream());
    }

}

关键提醒:  **********************包裹起来的代码是从数据库拿到的数据List集合 

这样就可以生成Excle表格了


二. Excle数据导入数据库

1.编写新增实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {

  @Value(value = "id")
  private long id;
  @Value(value = "数量")
  private long count;
  @Value(value = "姓名")
  private String name;
  @Value(value = "单价")
  private double price;
  @Value(value = "物品类型")
  private long type;
}

@Value属性是匹配Excle表格的标头名称

2.service层批量新增数据

    /**
     * 批量新增goods方法
     * @param list goods
     * @return 0
     */
    public int addAllGoods(List<Goods> list){
        for (int i = 0; i <list.size() ; i++) {
            if (list.get(i)==null){
                continue;
            }
            System.out.println(goodDao.insert(list.get(i)));
        }
        return 1;
    }

3.编写Excle导入工具类

public class ExcelImport {
    //上传的是以.xls后缀的
    private final static String excel2003L = ".xls";
    //上传的是以.xlsx后缀的
    private final static String excel2007U = ".xlsx";

    public static List<List<Object>> getListByExcel(InputStream in, String fileName) throws Exception {
        //创建 list 模拟Excel表结构
        List<List<Object>> list = null;

        //创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空!");
        }
        Sheet sheet = null;  //页数
        Row row = null;  //行数
        Cell cell = null;  //列数

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet页
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            //遍历当前sheet中的所有行
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null) {
                    continue;
                }

                //遍历所有的列
                List<Object> li = new ArrayList<Object>();
                for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                    //获取第i页第j行第y列的值
                    cell = row.getCell(y);
                    li.add(getValue(cell));
                }
                list.add(li);
            }
        }
        return list;
    }

    public static Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        //获取Excel后缀
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        //跟据后缀创建工作簿
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007+
        } else {
            throw new Exception("解析的文件格式有误!");
        }
        return wb;
    }

    public static String getValue(Cell cell) {
        String value = "";
        if (null == cell) {
            return value;
        }
        switch (cell.getCellType()) {
            //数值型
            case NUMERIC:
                if (DateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ,获取该cell的date值
                    Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    value = format.format(date);
                    ;
                } else {// 纯数字
                    BigDecimal big = new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if (null != value && !"".equals(value.trim())) {
                        String[] item = value.split("[.]");
                        if (1 < item.length && "0".equals(item[1])) {
                            value = item[0];
                        }
                    }
                }
                break;
            //字符串类型
            case STRING:
                //如果是string类型进行下划线转驼峰处理
                value = cell.getStringCellValue();
                break;
            // 公式类型
            case FORMULA:
                //读公式计算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
                    value = cell.getStringCellValue();
                }
                break;
            // 布尔类型
            case BOOLEAN:
                value = " " + cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue();
        }
        if ("null".endsWith(value.trim())) {
            value = "";
        }
        return value;
    }

    public static void setFileValueByFieldName(Object object, String fieldName, Object val) {
        //获取object类的所有属性
        Field[] fields = object.getClass().getDeclaredFields();
        try {
            //对所有属性进行遍历
            for (int i = 0; i < fields.length; i++) {
                //获取第i个属性
                Field field = fields[i];
                //如果Excel的某一列的列名(fieldName)与
                //在第i个属性上面添加的@Value注解的value一样,进行下面的操作
                if (fieldName.equals(field.getAnnotation(Value.class).value())) {
                    Class type = field.getType();
                    if (fieldName.equals("id")){
                        continue;
                    }
                    //如果field为私有属性,也可以对它进行操作
                    field.setAccessible(true);
                    //获取该属性的数据类型,如果是Integer类型的
                    if (field.getType()==double.class) {
                        field.set(object, Double.valueOf(val.toString()));
                        //如果时LocalDateTime类型的
                    } else if (type== int.class) {
                        //把val转成Integer存到该属性里面
                        field.set(object, Integer.valueOf(val.toString()));
                    } else if (field.getType()==long.class) {
                        field.set(object, Long.valueOf(val.toString()));
                        //如果时LocalDateTime类型的
                    } else if (field.getType() == LocalDateTime.class) {
                        //先把他格式化
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                        LocalDateTime time = LocalDateTime.parse(val.toString(), formatter);
                        field.set(object, time);
                        //如果其他类型的直接存
                    } else {
                        field.set(object, val);
                    }
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

--- 导入方法

setFileValueByFieldName(实体类Object,Excle表格的标头fileName,要注入的值var)

在该方法进行属性类型判定赋值

4.编写Controller

@Controller
@RequestMapping("/student")
public class StudentController {
    @Autowired
    goodServiceImpl goodService;

    @PostMapping("/upload")
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = "F:\\学习文档\\SSm\\SSm";
            // 为了防止文件名冲突,获取当前时间+文件原名生成新的文件名
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            // 上传文件
            File f = new File(filePath + fileName);
            file.transferTo(f);
            fileName = filePath + fileName;

            //输入流,获取刚刚上传文件转成输入流
            FileInputStream fileInputStream = new FileInputStream(new File(fileName));
            //定义一个list变量,模拟excel结构
            List<List<Object>> list = ExcelImport.getListByExcel(fileInputStream, fileName);
            //定义firstRows变量,用来获取第一行,就是标题,每列名字
            List<Object> firstRows = null;
            //定义studentList变量,用来存储文件内容(学生信息)
            List<Goods> studentList = new ArrayList<>();
            //如果 list 不为空,大小大于0则获取第一行存到firstRows 里面
            if (list != null && list.size() > 0) {
                firstRows = list.get(0);
            } else {
                //否则返回 failure
                return "表格数据为空";
            }


            //对list进行遍历,因为第一行是标题,不用存到数据库,所以从第二行开始遍历
            for (int i = 1; i < list.size(); i++) {
                //获取第i行数据
                List<Object> rows = list.get(i);
                //定义goods遍历,存储第i行数据
                Goods good = new Goods();


                //对第i行数据进行遍历,
                //从1开始是因为新增不能有id
                for (int j = 1; j < rows.size(); j++) {
                    //获取第i行第j列数据,存到cellVal 变量里面
                    String cellVal = (String) rows.get(j);
                    //调用setFileValueByFieldName函数,把数据存到student对应的属性里面
                    ExcelImport.setFileValueByFieldName(good, firstRows.get(j).toString().trim(), cellVal);
                }
                //把student变量加到studentList
                studentList.add(good);
            }
            //调用批量插入方法,把数据存到数据库
            int o= goodService.addAllGoods(studentList);
            if (o != 0) {
                return "成功了";
            } else {
                return "导入失败";
            }
        } catch (Exception e) {
            return "报错了";
        }
    }
}

**注意**

这里用的双重for循环便利赋值操作,如果第一行或第一列id无法正常新增,下标控制

五:前端导入页面

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>导入Excel</title>
</head>
<body>
<h1>选择Excel</h1>
<form th:action="@{/student/upload}" method="post" enctype="multipart/form-data">
    <!-- name 的值与@RequestParam的值相同-->
    <input type="file" name="file"/><br/>
    <input type="submit" value="上传"/><br/>
</form>

</body>
</html>

 三.echarts数据展示

声明:vue+echarts图标数据展示,柱状图,圆形图数据展示

1.创建Vue项目

可以看看我之前写的Vue文章

Springboot整合Mybatis,Vue实现三级联查(保姆级教程)_最爱香泡泡的博客-CSDN博客

2.安装Echarts

npm install echarts --save

在vue项目中引用Echarts

3.部署Echarts环境

import echarts from 'echarts'
Vue.prototype.$echarts = echarts

在main.js里导入echarts

在组件中直接引入

    import echarts from 'echarts'

4.便利数据到Series内

<template>
    <div id="myCharts" ref="love" style="width: 500px;height: 500px">
    </div>
</template>

<script>
    import echarts from 'echarts'
    import axios from 'axios'

    export default {
        name: 'OneVue',
        data() {
            return {
                serData: []
            }
        },
        mounted() {
            axios.get("http://localhost:8080/echarts/map").then(rep => {
                this.serData = rep.data;
                let myChart = echarts.init(this.$refs.love);
                // 指定图表的配置项和数据
                let option = {
                    title: {
                        text: '销量占比'
                    },
                    tooltip: {},
                    series: [
                        {
                            type: 'pie',
                            data:this.serData,
                            radius: "70%"
                        }
                    ]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            })
        }
    }
</script>

组件渲染比异步快,所以要把组件渲染丢到异步里先渲染数据在渲染组件

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值