Vue2+SpringBoot實現(xiàn)數(shù)據(jù)導出到csv文件并下載的使用示例
更新時間:2023年10月15日 15:33:27 作者:大米?
本文主要介紹了Vue2+SpringBoot實現(xiàn)數(shù)據(jù)導出到csv文件并下載,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
前言
- 該功能用于導出數(shù)據(jù)到
csv
文件,并且前端進行下載操作。 - 涉及到java后端以及前端。后端獲取數(shù)據(jù)并處理,前端獲取返回流并進行下載操作。
csv
與excel
文件不大相同。如果對導出的數(shù)據(jù)操作沒有很高要求的話,csv
文件就夠了。具體差異自行百度。- 我這里使用的數(shù)據(jù)是假數(shù)據(jù),并沒有從數(shù)據(jù)庫獲取。
使用csv
好處:
- 由于功能少,所以要比excel文件小,下載快。
- 后端不需要添加
apache-poi
等依賴,處理好數(shù)據(jù),返回值為字符串字節(jié)即可。
1、后端代碼
1.1、搭建springBoot項目
搭建項目就不說了,最基本的要求。不會的話需要先學習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 表內容的鍵值 * @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); } } // 寫出響應 os.write(buf.toString().getBytes("GBK")); os.flush(); } /** * 設置Header 輔助函數(shù), 可用可不用 * * @param fileName * @param response * @throws UnsupportedEncodingException */ public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException { // 設置文件后綴 SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String fn = fileName + sdf.format(new Date()) + ".csv"; // 讀取字符編碼 String utf = "UTF-8"; // 設置響應 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", // 列名對應的數(shù)據(jù)列的字段 outputStream); } }
2、前端代碼
2.1、搭建vue2框架
也是最基本的,就不說了。
2.2、調用接口,并進行下載
<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' // 設置響應結果類型為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、效果
到此這篇關于Vue2+SpringBoot實現(xiàn)數(shù)據(jù)導出到csv文件并下載的使用示例的文章就介紹到這了,更多相關Vue2 SpringBoot 數(shù)據(jù)導出內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
詳解vue axios用post提交的數(shù)據(jù)格式
這篇文章主要介紹了詳解vue axios用post提交的數(shù)據(jù)格式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08Vue.js實現(xiàn)在下拉列表區(qū)域外點擊即可關閉下拉列表的功能(自定義下拉列表)
這篇文章主要介紹了Vue.js實現(xiàn)在下拉列表區(qū)域外點擊即可關閉下拉列表的功能(自定義下拉列表) ,需要的朋友可以參考下2017-05-05