Vue2+SpringBoot實(shí)現(xiàn)數(shù)據(jù)導(dǎo)出到csv文件并下載的使用示例
前言
- 該功能用于導(dǎo)出數(shù)據(jù)到
csv文件,并且前端進(jìn)行下載操作。 - 涉及到j(luò)ava后端以及前端。后端獲取數(shù)據(jù)并處理,前端獲取返回流并進(jìn)行下載操作。
csv與excel文件不大相同。如果對(duì)導(dǎo)出的數(shù)據(jù)操作沒有很高要求的話,csv文件就夠了。具體差異自行百度。- 我這里使用的數(shù)據(jù)是假數(shù)據(jù),并沒有從數(shù)據(jù)庫(kù)獲取。
使用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", // 列名對(duì)應(yīng)的數(shù)據(jù)列的字段
outputStream);
}
}
2、前端代碼
2.1、搭建vue2框架
也是最基本的,就不說了。
2.2、調(diào)用接口,并進(jìn)行下載
<template>
<div class="home">
<button @click="downLoadFile">測(cè)試按鈕</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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue axios用post提交的數(shù)據(jù)格式
這篇文章主要介紹了詳解vue axios用post提交的數(shù)據(jù)格式,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-08-08
關(guān)于vxe-table復(fù)選框翻頁(yè)選中問題及解決
這篇文章主要介紹了關(guān)于vxe-table復(fù)選框翻頁(yè)選中問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
Vue.js實(shí)現(xiàn)在下拉列表區(qū)域外點(diǎn)擊即可關(guān)閉下拉列表的功能(自定義下拉列表)
這篇文章主要介紹了Vue.js實(shí)現(xiàn)在下拉列表區(qū)域外點(diǎn)擊即可關(guān)閉下拉列表的功能(自定義下拉列表) ,需要的朋友可以參考下2017-05-05
Vue實(shí)現(xiàn)自定義字段導(dǎo)出EXCEL的示例代碼
這篇文章主要介紹了Vue實(shí)現(xiàn)自定義字段導(dǎo)出EXCEL的示例代碼,代碼簡(jiǎn)單易懂,對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
vue中使用echarts制作圓環(huán)圖的實(shí)例代碼
這篇文章主要介紹了vue中使用echarts制作圓環(huán)圖的實(shí)例代碼,代碼簡(jiǎn)單易懂,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2018-07-07

