【Echarts】上传excle存入数据库,并画出对应柱状图。

2024-03-29 12:48

本文主要是介绍【Echarts】上传excle存入数据库,并画出对应柱状图。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

效果图:选择excel文件上传->存入数据库->返回List->显示对应图表

前端demo.html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>图表上传与显示</title><script src="https://cdn.staticfile.org/echarts/4.3.0/echarts.min.js"></script><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script><script src="https://unpkg.com/xlsx@0.13.3/dist/xlsx.full.min.js"></script><script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.js"></script><script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body><form method="POST" action="/file/excel" enctype="multipart/form-data"><input name="file" type="file" /><input type="submit" value="上传"></form><div id="main" style="width: 600px;height:400px;"></div><script type="text/javascript">var myChart = echarts.init(document.getElementById('main'));myChart.showLoading();  // 开启 loading 效果myChart.setOption({title: {text: '异步数据加载示例'},tooltip: {},legend: {data:['销量']},xAxis: {data: []},yAxis: {},series: [{name: '销量',type: 'bar',data: []}]});myChart.showLoading();    //数据加载完之前先显示一段简单的loading动画var names=[];    //类别数组(实际用来盛放X轴坐标值)var nums=[];    //销量数组(实际用来盛放Y坐标值)$.ajax({type : "post",async : true,            //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)url : "/list",    //请求发送到TestServlet处data : {},dataType : "json",        //返回数据形式为jsonsuccess : function(result) {//请求成功时执行该函数内容,result即为服务器返回的json对象if (result) {for(var i=0;i<result.length;i++){names.push(result[i].name);    //挨个取出类别并填入类别数组}for(var i=0;i<result.length;i++){nums.push(result[i].sale);    //挨个取出销量并填入销量数组}myChart.hideLoading();    //隐藏加载动画myChart.setOption({        //加载数据图表xAxis: {data: names},series: [{// 根据名字对应到相应的系列name: '销量',data: nums}]});}},error : function(errorMsg) {//请求失败时执行该函数alert("图表请求数据失败!");myChart.hideLoading();}})</script></body>
</html>

文件目录:(有些没有用到,如bean-ResponseBean是标准响应格式,因为这相应的不多我就没用,然后index.html是其他图形的,)

1.数据库设计:mybatis

1.1对象sales:

package com.example.charts.bean;public class sales {private int sid;private int year;private String name;private int sale;public sales() {}public sales(String name, int sale) {this.name = name;this.sale = sale;}public sales(int year, String name, int sale) {this.year = year;this.name = name;this.sale = sale;}public int getSid() {return sid;}public void setSid(int sid) {this.sid = sid;}public int getYear() {return year;}public void setYear(int year) {this.year = year;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getSale() {return sale;}public void setSale(int sale) {this.sale = sale;}
}

1.2 dbMapper.xml: 数据库映射

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 映射文件,映射到对应的SQL接口 -->
<mapper namespace="com.example.charts.DataMapper"><!--返回的结果集,用于关联实体类属性和数据库字段 --><!--如果实体类属性和数据库属性名保持一致,就不需要javaType和jdbcType(必须大写)属性 --><resultMap id="sales_resultMap" type="com.example.charts.bean.sales"><result column="sid" property="sid" javaType="java.lang.Integer" jdbcType="INTEGER" /><result column="name" property="name" javaType="java.lang.String" jdbcType="VARCHAR" /><result column="sale" property="sale" javaType="java.lang.Integer" jdbcType="INTEGER" /></resultMap><!-- 显示数据 --><select id="listALL" resultMap="sales_resultMap">select * from sales order by sid</select><!-- 插入数据 --><insert id="Insert" parameterType="com.example.charts.bean.sales">insert into sales (name,sale)values (#{name}, #{sale})</insert></mapper>

1.3 DataMapper:映射的接口

package com.example.charts;import com.example.charts.bean.sales;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;import java.util.List;//映射Sql,定义接口
@Mapper
@Component
public interface DataMapper {//显示List<sales> listALL();//插入void Insert(sales sa);
}

1.4 salesService:显示&插入

package com.example.charts.service;import com.example.charts.DataMapper;
import com.example.charts.bean.sales;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;@Service
public class salesService {@AutowiredDataMapper dataMapper;public List<sales> listALL(){return dataMapper.listALL();}public void ruleInsert(sales sale){dataMapper.Insert(sale);}
}

1.5 DataSourceConfig:数据库配置文件

package com.example.charts;import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;import javax.sql.DataSource;@Configuration
//指定扫描的mapper接口所在的包
@MapperScan(basePackages = "com.example.charts", sqlSessionFactoryRef = "DBDataSqlSessionFactory")
public class DataSourceConfig {@Bean(name = "DBDataSource")@ConfigurationProperties(prefix="spring.datasource") //告诉自动加载配置的属性public DataSource dataSource() {return DataSourceBuilder.create().build();}@Bean(name = "DBDataSqlSessionFactory")public SqlSessionFactory  sqlSessionFactory(@Qualifier("DBDataSource") DataSource dataSource)throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/dbMapper.xml"));return bean.getObject();}@Bean(name = "DBDataTransactionManager")public DataSourceTransactionManager transactionManager(@Qualifier("DBDataSource") DataSource dataSource) {return new DataSourceTransactionManager(dataSource);}@Bean(name = "DBDataSqlSessionTemplate")public SqlSessionTemplate sqlSessionTemplate(@Qualifier("DBDataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {return new SqlSessionTemplate(sqlSessionFactory);}
}

2.FileService:处理Excel文件,读取表格内容,调用DataMapper存入数据库。

package com.example.charts.service;import com.example.charts.DataMapper;
import com.example.charts.bean.sales;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;@Service
public class FileService {@AutowiredDataMapper dataMapper;public void insql(String filename) {try {// 构造 Workbook 对象,execelFile 是传入文件路径(获得Excel工作区)Workbook book = null;try {// Excel 2007 + WPS的exclebook = new XSSFWorkbook(new FileInputStream(filename));} catch (Exception ex) {// Excel 2003book = new HSSFWorkbook(new FileInputStream(filename));}// 读取表格的第一个sheet页Sheet sheet = book.getSheetAt(0);// 总行数,从0开始int totalRows = sheet.getLastRowNum();// 循环输出表格中的内容,首先循环取出行,再根据行循环取出列for (int i = 1; i <= totalRows; i++) {Row row = sheet.getRow(i);if (row == null) {    // 处理空行continue;}sales sa=new sales(row.getCell(0).toString(),(int)Math.ceil(Double.valueOf(row.getCell(1).toString())));//转成int类型dataMapper.Insert(sa); //插入数据}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

3.后端

3.1FileUploadController :将上传的excel存到项目中(根据上传日期新建文件夹),并调用FileService。

package com.example.charts.controller;import com.example.charts.bean.ResponseBean;
import com.example.charts.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;@RestController()
@RequestMapping("/file")
public class FileUploadController {@Autowiredprivate FileService fileService;/*** 实现文件上传* */@PostMapping("/excel")public ResponseBean fileUpload(@RequestParam("file") MultipartFile uploadfile) {if (uploadfile.isEmpty()) {return new ResponseBean(500,"error","文件上传失败");}SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");String format = sdf.format(new Date());File file = new File(format);String oldName = uploadfile.getOriginalFilename();assert oldName != null;String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."),oldName.length());String filename=file.getAbsolutePath() + File.separator + newName;File dest = new File(filename);if(!dest.isDirectory()){dest.mkdirs();//递归生成文件夹}try {uploadfile.transferTo(dest); //保存文件fileService.insql(filename); //调用自定义方法,把文件传给service处理return new ResponseBean(200,"succ",null);} catch (IllegalStateException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();return new ResponseBean(500,"error","文件上传失败");}}}

3.2 chart:也是一个controller

package com.example.charts.controller;import com.example.charts.bean.sales;
import com.example.charts.service.salesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;@Controller
public class chart {@Autowiredprivate salesService saleService;@RequestMapping("/show")public String show(){return "demo";}@ResponseBody@RequestMapping("/list")public List<sales> listAll() {List<sales> sale = saleService.listALL();return sale;}
}

 

这篇关于【Echarts】上传excle存入数据库,并画出对应柱状图。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/858633

相关文章

Oracle 数据库数据操作如何精通 INSERT, UPDATE, DELETE

《Oracle数据库数据操作如何精通INSERT,UPDATE,DELETE》在Oracle数据库中,对表内数据进行增加、修改和删除操作是通过数据操作语言来完成的,下面给大家介绍Oracle数... 目录思维导图一、插入数据 (INSERT)1.1 插入单行数据,指定所有列的值语法:1.2 插入单行数据,指

k8s上运行的mysql、mariadb数据库的备份记录(支持x86和arm两种架构)

《k8s上运行的mysql、mariadb数据库的备份记录(支持x86和arm两种架构)》本文记录在K8s上运行的MySQL/MariaDB备份方案,通过工具容器执行mysqldump,结合定时任务实... 目录前言一、获取需要备份的数据库的信息二、备份步骤1.准备工作(X86)1.准备工作(arm)2.手

PostgreSQL数据库密码被遗忘时的操作步骤

《PostgreSQL数据库密码被遗忘时的操作步骤》密码遗忘是常见的用户问题,因此提供一种安全的遗忘密码找回机制是十分必要的,:本文主要介绍PostgreSQL数据库密码被遗忘时的操作步骤的相关资... 目录前言一、背景知识二、Windows环境下的解决步骤1. 找到PostgreSQL安装目录2. 修改p

SQL Server修改数据库名及物理数据文件名操作步骤

《SQLServer修改数据库名及物理数据文件名操作步骤》在SQLServer中重命名数据库是一个常见的操作,但需要确保用户具有足够的权限来执行此操作,:本文主要介绍SQLServer修改数据... 目录一、背景介绍二、操作步骤2.1 设置为单用户模式(断开连接)2.2 修改数据库名称2.3 查找逻辑文件名

SQL Server数据库死锁处理超详细攻略

《SQLServer数据库死锁处理超详细攻略》SQLServer作为主流数据库管理系统,在高并发场景下可能面临死锁问题,影响系统性能和稳定性,这篇文章主要给大家介绍了关于SQLServer数据库死... 目录一、引言二、查询 Sqlserver 中造成死锁的 SPID三、用内置函数查询执行信息1. sp_w

Druid连接池实现自定义数据库密码加解密功能

《Druid连接池实现自定义数据库密码加解密功能》在现代应用开发中,数据安全是至关重要的,本文将介绍如何在​​Druid​​连接池中实现自定义的数据库密码加解密功能,有需要的小伙伴可以参考一下... 目录1. 环境准备2. 密码加密算法的选择3. 自定义 ​​DruidDataSource​​ 的密码解密3

Maven项目中集成数据库文档生成工具的操作步骤

《Maven项目中集成数据库文档生成工具的操作步骤》在Maven项目中,可以通过集成数据库文档生成工具来自动生成数据库文档,本文为大家整理了使用screw-maven-plugin(推荐)的完... 目录1. 添加插件配置到 pom.XML2. 配置数据库信息3. 执行生成命令4. 高级配置选项5. 注意事

mybatis的mapper对应的xml写法及配置详解

《mybatis的mapper对应的xml写法及配置详解》这篇文章给大家介绍mybatis的mapper对应的xml写法及配置详解,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录前置mapper 对应 XML 基础配置mapper 对应 xml 复杂配置Mapper 中的相

在Java中基于Geotools对PostGIS数据库的空间查询实践教程

《在Java中基于Geotools对PostGIS数据库的空间查询实践教程》本文将深入探讨这一实践,从连接配置到复杂空间查询操作,包括点查询、区域范围查询以及空间关系判断等,全方位展示如何在Java环... 目录前言一、相关技术背景介绍1、评价对象AOI2、数据处理流程二、对AOI空间范围查询实践1、空间查

Python+PyQt5实现MySQL数据库备份神器

《Python+PyQt5实现MySQL数据库备份神器》在数据库管理工作中,定期备份是确保数据安全的重要措施,本文将介绍如何使用Python+PyQt5开发一个高颜值,多功能的MySQL数据库备份工具... 目录概述功能特性核心功能矩阵特色功能界面展示主界面设计动态效果演示使用教程环境准备操作流程代码深度解