Vue imports Echarts to realize scatter graph Axios parses excel flow data echarts data visualization front-end display

        In order to download the xlsx file from the local server and display it in the front-end vue echarts, many pitfalls have been stepped on, and the complete process and source code are now shared.

1. The vue axios get request returns 304 Not Modified without updating the data

Reason: Since the browser caches the get request, the data will not be updated no matter how it is refreshed. 

var url = 'http://127.0.0.1:8000/' + this.value.value + '?nocache=' + (new Date()).getTime() // 本地数据库下载
axios.get(url,{ responseType: "arraybuffer" })

Solution: Add '?nocache=' + (new Date()).getTime() at the end of the url  

Add a nocache parameter to the url object, the attribute is timestamp, and the value is a timestamp. The principle is to change the url in real time. When the browser judges that the cache content is different, it will update the data normally.

2. Obtain and parse xlsx file stream data

axios.get(url,{ responseType: "arraybuffer" })
        .then((res) => {
          console.log("res:" + res)
          console.log("res.data:" + res.data)
          
          let wb = XLSX.read(res.data, {
						type: 'arraybuffer'
					});
          
          //wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
		  //wb.Sheets[Sheet名]获取第一个Sheet的数据
          let worksheet = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])); // 将一个 JavaScript 对象或值转换为 JSON 字符串
          console.log('worksheet:' + worksheet)

You can use the get method of axios to send an HTTP request to obtain the binary stream data of the Excel file. In the request, the responseType needs to be set to arraybuffer.

After getting the Excel file stream data, you can use the wb.Sheets[wb.SheetNames[0]] function to get the data of the first Sheet in Sheets. Use the plug-in SheetJS to use XLSX.utils.sheet_to_json() to parse excel, and assign empty cells to empty strings. Finally use JSON.stringify() to convert the object to a JSON string.

Contents of xlsx file stored locally, y = 2x for simple linear regression:

Let's print the worksheet to see the string content:

 3. Process the Json string and display it visually by the front-end echarts

 Convert Json string to two-dimensional array:

var axisData = []
for( var i = 0;i < myobj.length; i++) {
    var x = myobj[i].x
    var y = myobj[i].y
    var newArr = [x,y]
}
console.log("axisData:" + axisData);

The content of printing the two-dimensional array axisData is as follows:

The blogger has tried many methods, but only the two-dimensional array echarts generated by the above function conversion will be displayed normally.

The following are other methods of trying to convert Json to an array, but echarts cannot recognize them. If you understand, please leave a message to explain.

// 获取二维数组第一种方法
          const array = [[]];
          for(var i = 0;i < myobj.length; i++){
            array[i] = [];
            for(var j=0;j<2;j++){
              if(j==0){
                var x = myobj[i].x;
                array[i][j] = x;
                console.log("array[i][j]:"+array[i][j]);
              } else if (j==1) {
                var y = myobj[i].y;
                array[i][j] = y;
                console.log("array[i][j]:"+array[i][j]);
              }
            }
          }

// 获取二维数组第二种方法
          let array2 = new Array(myobj.length);   //动态定义一个二维数组
          for(let i=0;i<array2.length;i++){
            array2[i] = new Array(2);
            for(var j=0;j<2;j++){
              if(j==0){
                var x = myobj[i].x;
                array2[i][j] = x;
                console.log("array2[i][j]:"+array2[i][j]);
              } else if (j==1){
                var y = myobj[i].y;
                array2[i][j] = y;
                console.log("array2[i][j]:"+array2[i][j]);
              }
            }
          }
          this.arrActive2 = {...array2};   //形同于arrActive2=[['','',''],['','',''],['','','']]
          console.log("this.arrActive2" + this.arrActive2);

Finally, pass the axisData two-dimensional array to the echarts component

echarts.init(document.getElementById('chart')).setOption({
    xAxis: { triggerEvent: true }, // 允许点击X轴(y轴需要点击也是要加这句话)
    yAxis: { triggerEvent: true },
    series: [
        {
            symbolSize: 20,
            data: axisData,
            type: 'scatter'
        }
    ]
})

The user selects the imported xlsx data file, clicks the "Display" button, and the scatter plot of the visualized results is displayed below the button. The complete effect is as follows:

 4. Complete front-end source code

<script>
import * as api from './api'
import { crudOptions } from './crud'
import { d2CrudPlus } from 'd2-crud-plus'
import * as echarts from 'echarts'
import * as XLSX from 'xlsx'
import { request } from '@/api/service'
import { AddObj, GetList, UpdateObj, DelObj } from './api' // 查询添加修改删除的http请求接口
import axios from 'axios' // Axios是一个基于promise的HTTP库(类似于jQuery的Ajax,用于HTTP请求)可以用于浏览器和node.js(既可以用于客户端也可以用于node.js编写的服务端)
// import { process_chart_data1 } from './process_data.js'
export default {
  name: 'echarts',
  mixins: [d2CrudPlus.crud],
  mounted () {
    this.pageRequest().then((res) => {
      const resList = res.data.data
      resList.forEach((val, index) => {
        this.dataList.push({
          value: val.file_url,
          label: val.name
        })
      })
      console.log(this.dataList)
    })
  },
  data () {
    return {
      form: {},
      dataList: [],
      value: ''
    }
  },
  methods: {
    change (val) {
      console.log(val)
    },
    onSubmit () {
      // 在这设置图表option
      // api
      //   .getFileData({
      //     filePath: 'this.value.value'
      //   })
      var url = 'http://127.0.0.1:8000/' + this.value.value + '?nocache=' + (new Date()).getTime() // 本地数据库下载
      axios.get(url, { responseType: 'arraybuffer' })
        .then((res) => {
          console.log('res:' + res)
          console.log('res.data:' + res.data)
          // let str = String.fromCharCode.apply(null, new Uint16Array(res.data)) // ArrayBuffer转为字符串,参数为ArrayBuffer对象
          const wb = XLSX.read(res.data, {
            type: 'arraybuffer'
          })
          // this.handle(wb);
          // wb.SheetNames[0]是获取Sheets中第一个Sheet的名字
          // wb.Sheets[Sheet名]获取第一个Sheet的数据
          const worksheet = JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])) // 将一个 JavaScript 对象或值转换为 JSON 字符串
          console.log('worksheet:' + worksheet)
          // this.worksheet是读入的JSON文件的数据,读出的数据时对象类型,要转为数组才行
          // const obj= JSON.stringify(worksheet);
          // var arr = [];
          // for(let key in obj){
          //   arr.push(obj[key])
          // }
          // console.log("arr" + arr); // ",[,{,\,",x,\,",:,1,,,\,",y,\,",:,2,},,,{,\,",x,\,",:,2,,,\,",y,\,",:,4,},,,{,\,",x,\,",:,3,.,5,,,\,",y,\,",:,7,},,,{,\,",x,\,",:,4,,,\,",y,\,",:,8,},],"
          // var myobj = worksheet;
          // eslint-disable-next-line no-eval
          var myobj = eval('(' + worksheet + ')') // 将字符串str当成有效的表达式来求值并返回计算结果

          // 获取二维数组第一种方法
          // const array = [[]];
          // for(var i = 0;i < myobj.length; i++){
          //   array[i] = [];
          //   for(var j=0;j<2;j++){
          //     if(j==0){
          //       var x = myobj[i].x;
          //       array[i][j] = x;
          //       console.log("array[i][j]:"+array[i][j]);
          //     } else if (j==1) {
          //       var y = myobj[i].y;
          //       array[i][j] = y;
          //       console.log("array[i][j]:"+array[i][j]);
          //     }
          //   }
          // }

          // 获取二维数组第二种方法
          // let array2 = new Array(myobj.length);   //动态定义一个二维数组
          // for(let i=0;i<array2.length;i++){
          //   array2[i] = new Array(2);
          //   for(var j=0;j<2;j++){
          //     if(j==0){
          //       var x = myobj[i].x;
          //       array2[i][j] = x;
          //       console.log("array2[i][j]:"+array2[i][j]);
          //     } else if (j==1){
          //       var y = myobj[i].y;
          //       array2[i][j] = y;
          //       console.log("array2[i][j]:"+array2[i][j]);
          //     }
          //   }
          // }
          // this.arrActive2 = {...array2};   //形同于arrActive2=[['','',''],['','',''],['','','']]
          // console.log("this.arrActive2" + this.arrActive2);

          var axisData = []
          for (var i = 0; i < myobj.length; i++) {
            var x = myobj[i].x
            var y = myobj[i].y
            var newArr = [x, y]
            axisData.push(newArr)
          }
          console.log('axisData:' + axisData)

          // 解析excel
          // this.analysisExcel(file).then((tableJson) => {
          //   if (tableJson && tableJson.length > 0) {
          //     //成功解析出数据
          //     //只取第一个sheet的数据
          //     let dataExcel = tableJson[0];
          //     console.log("数据", dataExcel);
          //     console.log(JSON.stringify(dataExcel.sheet));
          //   }
          // });

          console.log('this.value.label' + this.value.label)
          this.data = axisData
          // this.data = res.data.data
          switch (this.value.label) {
            case '逻辑回归.xlsx':
              echarts.init(document.getElementById('chart')).setOption({
                xAxis: {},
                yAxis: {},
                series: [
                  {
                    symbolSize: 20,
                    data: this.data,
                    type: 'scatter'
                  }
                ]
              })
              break
            case '线性回归.xlsx':
              echarts.init(document.getElementById('chart')).setOption({
                xAxis: { triggerEvent: true }, // 允许点击X轴(y轴需要点击也是要加这句话)
                yAxis: { triggerEvent: true },
                series: [
                  {
                    symbolSize: 20,
                    data: axisData,
                    type: 'scatter'
                  }
                ]
              })
              break

            default:
              break
          }
        })
    },
    getCrudOptions () {
      return crudOptions(this)
    },
    pageRequest (query) {
      return GetList(query)
    },
    addRequest (row) {
      console.log('api', api)
      return AddObj(row)
    },
    updateRequest (row) {
      console.log('----', row)
      return UpdateObj(row)
    },
    delRequest (row) {
      return DelObj(row.id)
    }
  }
}
</script>

Guess you like

Origin blog.csdn.net/Next_SummerAgain/article/details/131761525
Recommended