欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue2+SpringBoot實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出到csv文件并下載的使用示例

 更新時(shí)間:2023年10月15日 15:33:27   作者:大米?  
本文主要介紹了Vue2+SpringBoot實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出到csv文件并下載,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

前言

  • 該功能用于導(dǎo)出數(shù)據(jù)到csv文件,并且前端進(jìn)行下載操作。
  • 涉及到j(luò)ava后端以及前端。后端獲取數(shù)據(jù)并處理,前端獲取返回流并進(jìn)行下載操作。
  • csvexcel文件不大相同。如果對導(dǎo)出的數(shù)據(jù)操作沒有很高要求的話,csv文件就夠了。具體差異自行百度。
  • 我這里使用的數(shù)據(jù)是假數(shù)據(jù),并沒有從數(shù)據(jù)庫獲取。

使用csv好處:

  • 由于功能少,所以要比excel文件小,下載快。
  • 后端不需要添加apache-poi等依賴,處理好數(shù)據(jù),返回值為字符串字節(jié)即可。

1、后端代碼

1.1、搭建springBoot項(xiàng)目

搭建項(xiàng)目就不說了,最基本的要求。不會(huì)的話需要先學(xué)習(xí)springBoot(下面演示是基于springBoot的)。

1.2、創(chuàng)建CSV工具類

package com.tcc.utils;

import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CsvUtils {
    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = "\r\n";

    /**
     * @param dataList 集合數(shù)據(jù)
     * @param titles   表頭部數(shù)據(jù)
     * @param keys     表內(nèi)容的鍵值
     * @param os       輸出流
     */
    public static void doExport(List<Map<String, Object>> dataList, String titles, String keys, OutputStream os)
            throws Exception {

        // 保證線程安全
        StringBuffer buf = new StringBuffer();

        String[] titleArr = null;
        String[] keyArr = null;

        titleArr = titles.split(",");
        keyArr = keys.split(",");

        // 組裝表頭
        for (String title : titleArr) {
            buf.append(title).append(CSV_COLUMN_SEPARATOR);
        }
        buf.append(CSV_ROW_SEPARATOR);
        // 組裝數(shù)據(jù)
        if (!CollectionUtils.isEmpty(dataList)) {
            for (Map<String, Object> data : dataList) {
                for (String key : keyArr) {
                    buf.append("\t" +data.get(key)).append(CSV_COLUMN_SEPARATOR);
                }
                buf.append(CSV_ROW_SEPARATOR);
            }
        }

        // 寫出響應(yīng)
        os.write(buf.toString().getBytes("GBK"));
        os.flush();
    }

    /**
     * 設(shè)置Header 輔助函數(shù), 可用可不用
     *
     * @param fileName
     * @param response
     * @throws UnsupportedEncodingException
     */
    public static void responseSetProperties(String fileName, HttpServletResponse response)
            throws UnsupportedEncodingException {
        // 設(shè)置文件后綴
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = fileName + sdf.format(new Date()) + ".csv";
        // 讀取字符編碼
        String utf = "UTF-8";

        // 設(shè)置響應(yīng)
        response.setContentType("application/ms-txt.numberformat:@");
        response.setCharacterEncoding(utf);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
    }
}

1.3、編寫接口

package com.tcc.controller;

import com.tcc.utils.CsvUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @RequestMapping("generateCSV")
    // 解決跨域問題
    @CrossOrigin
    public void generateCSV(HttpServletResponse response) throws Exception {
        ServletOutputStream outputStream = response.getOutputStream();

        List<Map<String, Object>> dataList = new ArrayList();
        HashMap<String, Object> map = new HashMap<>();
        // 第一條數(shù)據(jù)
        map.put("name", "張三");
        map.put("age", 20);
        map.put("sex", "男");
        map.put("brithday",  new Date());
        dataList.add(map);

        // 第二條數(shù)據(jù)
        map = new HashMap<>();
        map.put("name", "李四");
        map.put("age", 22);
        map.put("sex", "女");
        map.put("brithday",  new Date());
        dataList.add(map);

        // 輔助函數(shù),可用可不用
//        CsvUtils.responseSetProperties("test", response);
        CsvUtils.doExport(dataList,
                "姓名,年齡,性別,生日", // 所有列名
                "name,age,sex,brithday", // 列名對應(yīng)的數(shù)據(jù)列的字段
                outputStream);
    }
}

2、前端代碼

2.1、搭建vue2框架

也是最基本的,就不說了。

2.2、調(diào)用接口,并進(jìn)行下載

<template>
  <div class="home">
    <button @click="downLoadFile">測試按鈕</button>
  </div>
</template>

<script>
export default {
  name: 'HomeView',
  methods: {
    downLoadFile() {
      this.axios.post("http://localhost:8080/demo/generateCSV", {}, {
        responseType: 'blob' // 設(shè)置響應(yīng)結(jié)果類型為blob類型
      }).then(res => {
         // 處理數(shù)據(jù),并下載
        const blob = new Blob([res.data]);
        let url = window.URL.createObjectURL(blob)
        let link = document.createElement('a')
        link.href = url
        link.setAttribute('download', 'test.csv')
        document.body.appendChild(link)
        link.click()
      })
    }
  }
}
</script>

3、效果

到此這篇關(guān)于Vue2+SpringBoot實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出到csv文件并下載的使用示例的文章就介紹到這了,更多相關(guān)Vue2 SpringBoot 數(shù)據(jù)導(dǎo)出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論