csv導出文件解決中文亂碼和文件名空格問題 csv導出文件解決中文亂碼和文件名空格問題

csv導出文件解決中文亂碼和文件名空格問題

開發環境

前端:Vue

後端:Java

問題的出現:

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

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

3、文件名是中文,出現亂碼

要注意的幾個問題:

1、文件名爲中文

2、文件名中有空格

3、文件內容有中文

以上問題都需要處理

處理方法

前端:

對於文件名的處理:

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

對於中文內容亂碼的處理:

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'

/**
 * 導出 CSV 文件下載
 * @param _this 上下文
 * @param url 請求地址
 * @param params 請求參數
 * @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 // 登錄中,默認帶用戶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轉義處理

且對於文件名中有空格而言,會轉爲%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文件導出工具實現類
 *
 * @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;
    }
}

最後

以上問題,不僅針對於導出csv,一切導出下載文件,皆可適用,僅供參考。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章