csv導(dǎo)出文件解決中文亂碼和文件名空格問題

csv導(dǎo)出文件解決中文亂碼和文件名空格問題

開發(fā)環(huán)境

前端:Vue

后端:Java

問題的出現(xiàn):

1、csv的文件中文內(nèi)容 excel打開是亂碼,wps沒問題(wps會進行不同的編碼轉(zhuǎn)換,excel不會)

2、其他未出現(xiàn)但潛在的問題(文件名中帶空格,xxx xxx.csv最后變成的xxx+xxx.csv)

3、文件名是中文,出現(xiàn)亂碼

要注意的幾個問題:

1、文件名為中文

2、文件名中有空格

3、文件內(nèi)容有中文

以上問題都需要處理

處理方法

前端:

對于文件名的處理:

把從content-disposition里面獲取的fileName進行decodeURI處理

對于中文內(nèi)容亂碼的處理:

httprequest的responseType要添加為blob responseType: 'blob'

核心代碼
 _this.$axios({
        method: 'get',
        url: origin + url,
        params,
        headers,
        responseType: 'blob',    //重點代碼
        timeout: 30000
    }).then(res => {
const disposition = res.headers['content-disposition']
            let fName = decodeURI(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length))
            fName = fName.replace(/"/g, '')
            link.download = fName
參考代碼
import env from '../env'

/**
 * 導(dǎo)出 CSV 文件下載
 * @param _this 上下文
 * @param url 請求地址
 * @param params 請求參數(shù)
 * @param fileName 文件名(需要帶后綴, 如果傳 false/null/undefined 可直接使用后臺返回的文件名)
 * @param loadingName loading 掛載在 _this 上的名字
 */
export const downloadCSV = (_this, url, params, fileName, loadingName) => {
    _this[loadingName] = true
    const origin = process.env.NODE_ENV === 'localDevelopment' ? process.env.BASE_URL : window.location.origin + process.env.BASE_URL
    const headers = {}
    let downloadUrl = ''
    if (_this.$store.state.user.token) {
        headers.userId = _this.$store.state.user.userId // 登錄中,默認(rèn)帶用戶ID
        headers.Token = _this.$store.state.user.token // 請求接口決定是否帶Token
    }
    _this.$axios({
        method: 'get',
        url: origin + url,
        params,
        headers,
        responseType: 'blob',
        timeout: 30000
    }).then(res => {
        downloadUrl = window.URL.createObjectURL(new Blob([res.data]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = downloadUrl
        if (fileName) {
            link.download = fileName
        } else {
            const disposition = res.headers['content-disposition']
            let fName = decodeURI(disposition.substring(disposition.indexOf('filename=') + 9, disposition.length))
            fName = fName.replace(/"/g, '')
            link.download = fName
        }
        document.body.appendChild(link)
        link.click()
    }).finally(() => {
        _this[loadingName] = false
        window.URL.revokeObjectURL(downloadUrl)
    })
}

后端:

對于文件名處理:

里面fileName需要UrlEncoder進行url轉(zhuǎn)義處理

且對于文件名中有空格而言,會轉(zhuǎn)為%x%x+%x%x.csv 這里會替換+為%20

核心代碼
 @Override
    public ResponseEntity<byte[]> toResponse() {
        this.close();
        try {
            FileInputStream fis = new FileInputStream(this.csvFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            HttpHeaders httpHeaders = new HttpHeaders();
            String encodeName = URLEncoder.encode(this.name + SUFFIX, "UTF-8");
            String fileName = encodeName.replace("+", "%20");
            httpHeaders.setContentDispositionFormData("attachment", fileName);
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));
            return new ResponseEntity<>(bos.toByteArray(), httpHeaders, HttpStatus.CREATED);
        } catch (IOException e) {
            throw new BaseException(CSV_IO_EXCEPTION);
        }
    }
參考代碼
import lombok.Getter;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.stream.Stream;


/**
 * Csv文件導(dǎo)出工具實現(xiàn)類
 *
 * @author hx
 * @version 1.0
 * @date 2021/5/25 16:45
 */


@Getter
public class CsvUtil implements FileUtil {
    private static final String PREFIX = "vehicle";
    private static final String SUFFIX = ".csv";
    private final String name;
    private String[] headers;
    private FileOutputStream fos;
    private File csvFile;
    private String inCharset;
    private String outCharset;
    private OutputStreamWriter osw;
    private CSVPrinter csvPrinter;

    public CsvUtil(String name) {
        this(name, "UTF-8", "iso-8859-1");
    }

    public CsvUtil(String name, String inCharset, String outCharset) {
        this.name = name;
        this.inCharset = inCharset;
        this.outCharset = outCharset;
    }

    @Override
    public void setHeader(String... headers) {
        this.setHeaders(headers);
    }

    @Override
    public void setHeaders(String[] headers) {
        this.headers = headers;
        this.initPrinter();
    }

    @Override
    public void setHeaders(Collection<String> row) {
        this.setHeaders(row.toArray(new String[0]));
    }

    @Override
    public void writeVaried(Iterable<?> row) {
        try {
            this.csvPrinter.printRecord(row);
        } catch (IOException e) {
            throw new BaseException(CSV_IO_EXCEPTION);
        } catch (NullPointerException e) {
            this.initPrinter();
            this.writeVaried(row);
        }
    }


    @Override
    public void writeRow(Object[] row) {
        try {
            this.csvPrinter.printRecord(row);
        } catch (IOException e) {
            throw new BaseException(CSV_IO_EXCEPTION);
        } catch (NullPointerException e) {
            this.initPrinter();
            this.writeRow(row);
        }
    }


    @Override
    public void writeFeed() {
        try {
            this.csvPrinter.println();
        } catch (IOException e) {
            throw new BaseException(CSV_IO_EXCEPTION);
        } catch (NullPointerException e) {
            this.initPrinter();
            this.writeFeed();
        }
    }

    @Override
    public void writeEmptyLine() {
        try {
            this.csvPrinter.println();
        } catch (IOException e) {
            this.writeLine("");
        } catch (NullPointerException e) {
            this.initPrinter();
            this.writeEmptyLine();
        }
    }

    @Override
    public void writeLine(Object... line) {
        this.writeRow(line);
    }

    @Override
    public void writeStrLine(String... line) {
        Stream<String> stream = Arrays.stream(line);
        this.writeVaried(FileUtil.filterStrStream(stream));
    }

    @Override
    public void writeStrRow(String[] row) {
        Stream<String> stream = Arrays.stream(row);
        this.writeVaried(FileUtil.filterStrStream(stream));
    }

    @Override
    public void writeList(Collection<?> row) {
        this.writeVaried(row);
    }

    @Override
    public void writeStrList(Collection<String> row) {
        this.writeVaried(FileUtil.filterStrStream(row.stream()));
    }


    @Override
    public ResponseEntity<byte[]> toResponse() {
        this.close();
        try {
            FileInputStream fis = new FileInputStream(this.csvFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            HttpHeaders httpHeaders = new HttpHeaders();
            String encodeName = URLEncoder.encode(this.name + SUFFIX, "UTF-8");
            String fileName = encodeName.replace("+", "%20");
            httpHeaders.setContentDispositionFormData("attachment", fileName);
            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));
            return new ResponseEntity<>(bos.toByteArray(), httpHeaders, HttpStatus.CREATED);
        } catch (IOException e) {
            throw new BaseException(CSV_IO_EXCEPTION);
        }
    }

    @Override
    public void close() {
        FileUtil.close(csvPrinter, osw, fos);
    }

    private void initPrinter() {
        CSVFormat csvFormat = CSVFormat.DEFAULT;
        if (this.headers != null) {
            csvFormat = csvFormat.withHeader(this.headers);
        }
        try {
            this.csvFile = File.createTempFile(PREFIX, SUFFIX);
            this.fos = new FileOutputStream(this.csvFile);
            this.osw = new OutputStreamWriter(fos);
            //防止excel中文亂碼
            this.osw.write('\ufeff');
            this.osw.flush();
            this.csvPrinter = new CSVPrinter(this.osw, csvFormat);
        } catch (IOException e) {
            this.close();
            throw new BaseException(CSV_IO_EXCEPTION);
        }
    }

    public void setInCharset(String inCharset) {
        this.inCharset = inCharset;
    }

    public void setOutCharset(String outCharset) {
        this.outCharset = outCharset;
    }
}

最后

以上問題,不僅針對于導(dǎo)出csv,一切導(dǎo)出下載文件,皆可適用,僅供參考。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容