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 = place(/"/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 = v.NODE_ENV === 'localDevelopment' ? v.BASE_URL : igin + v.BASE_URL    const headers = {}
let downloadUrl = ''
if (_this.$store.ken) {
headers.userId = _this.$store.state.user.userId // 登录中,默认带⽤户ID
headers.Token = _this.$store.ken // 请求接⼝决定是否带Token
}
_this.$axios({
method: 'get',
url: origin + url,
params,
headers,
responseType: 'blob',
timeout: 30000
}).then(res => {
downloadUrl = ateObjectURL(new Blob([res.data]))
const link = ateElement('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 = place(/"/g, '')
link.download = fName
}
document.body.appendChild(link)
link.click()
}).finally(() => {
_this[loadingName] = false
vokeObjectURL(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 = ad(b))!=-1){
bos.write(b,0, n);
}
fis.close();
bos.close();
HttpHeaders httpHeaders =new HttpHeaders();
宫锁珠帘 百合String encodeName = de(this.name + SUFFIX,"UTF-8");
String fileName = place("+","%20");
httpHeaders.setContentDispositionFormData("attachment", fileName);
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));
return new ResponseEntity<>(ByteArray(), httpHeaders, HttpStatus.CREATED);
皮草怎么洗}catch(IOException e){
throw new BaseException(CSV_IO_EXCEPTION);
}
}
参考代码
import Getter;
import CSVFormat;
import CSVPrinter;
import HttpHeaders;
import HttpStatus;
import MediaType;
import ResponseEntity;
import*;
import URLEncoder;
import Arrays;
import Collection;
import Collections;
import 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");
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 headers){
this.setHeaders(headers);
}
@Override
public void setHeaders(String[] headers){
this.headers = headers;
this.initPrinter();
}
@Override
public void setHeaders(Collection<String> row){
this.Array(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{
try{
this.csvPrinter.println();
}catch(IOException e){
this.writeLine("");
}catch(NullPointerException e){
this.initPrinter();
this.writeEmptyLine();
}
}
@Override
public void line){
this.writeRow(line);
}
@Override
public void 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();
6个字的游戏名字try{
FileInputStream fis =new FileInputStream(this.csvFile);
ByteArrayOutputStream bos =new ByteArrayOutputStream();
byte[] b =new byte[1024];
int n;
while((n = ad(b))!=-1){
bos.write(b,0, n);
}
fis.close();
bos.close();
HttpHeaders httpHeaders =new HttpHeaders();
String encodeName = de(this.name + SUFFIX,"UTF-8");
String fileName = place("+","%20");
httpHeaders.setContentDispositionFormData("attachment", fileName);
httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
httpHeaders.setAccessControlExposeHeaders(Collections.singletonList("Content-Disposition"));
return new ResponseEntity<>(ByteArray(), httpHeaders, HttpStatus.CREATED);
}catch(IOException e){
throw new BaseException(CSV_IO_EXCEPTION);
}
}
@Override
public void close(){
FileUtil.close(csvPrinter, osw, fos);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。