1.原生ajax
var xhr = new XMLHttpRequest();
xhr.open('POST', SERVER_URL + "daily/exportCsv", true);
xhr.responseType = "blob"; // blob
xhr.setRequestHeader("Authorization", token)
xhr.onload = function () {
if (this.status === 200) {
// 返回200
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob); // base64
reader.onload = function (e) {
var a = document.createElement('a');
a.download = 'data.xlsx';
a.href = e.target.result;
$("body").append(a);
a.click();
$(a).remove();
}
}
};
//ajax
xhr.send()
2.axios 【vue 整个 axios,请见下篇,this.ajax 是axios 的vue实体内封装名】
exportData() {
this.$ajax({
method: 'get',
url: '/dailyCsv/exportCsv?driverId=' + this.formSelect.driverId + "&startDate=" + this.formSelect.startDate + "&endDate=" + this.formSelect.endDate,
responseType: 'blob'
}).then(response => {
console.log(response);
this.download(response)
}).catch((error) => {
})
}
上段代码里的 download 方法
download (data) {
if (!data) {
return
}
// let url = window.URL.createObjectURL(new Blob([data]))
// let link = document.createElement('a')
// link.style.display = 'none'
// link.href = url
// link.setAttribute('download', 'excel.csv')
// document.body.appendChild(link)
// link.click()
let blob = data;
let reader = new FileReader();
reader.readAsDataURL(blob); // base64
reader.onload = function (e) {
let a = document.createElement('a');
a.download = 'data.csv';
a.href = e.target.result;
document.body.appendChild(a)
a.click();
document.body.removeChild(a)
}
},
3.window.open()
SERVER_URL 是服务器域名端口号 链接的后台服务器【前后端分离项目】
window.open(encodeURI(SERVER_URL + "/dailyCsv/exportCsv?driverId=" + this.formSelect.driverId + "&startDate=" + this.formSelect.startDate + "&endDate=" + this.formSelect.endDate + "&Authorization=Bearer " + localStorage.getItem("TOKEN")));
后台核心代码 导出excel表格方法 :
public ResponseEntity exportCsv(DailyInput dailyInput){
String CSV_SEPERATOR = ",";
ContentDisposition contentDisposition = null;
try {
contentDisposition = ContentDisposition.type("attachment")
.fileName(URLEncoder.encode("配送日報", "UTF-8") + ".csv").build();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final PipedOutputStream output = new PipedOutputStream();
PipedInputStream input = null;
try {
input = new PipedInputStream(output);
} catch (IOException e) {
e.printStackTrace();
}
List list = extDailyRepository.searchListByVehicleCsv(dailyInput);
Runnable writer = new Runnable() {
@Override
public void run() {
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(output,"Shift_JIS"));) {
StringBuilder sb = new StringBuilder();
sb.append("車両名").append(CSV_SEPERATOR)
.append("車種").append(CSV_SEPERATOR)
.append("ドライバ名").append(CSV_SEPERATOR)
.append("積日").append(CSV_SEPERATOR)
.append("走行距離").append(CSV_SEPERATOR)
.append("得意先名").append(CSV_SEPERATOR)
.append("品名").append(CSV_SEPERATOR)
.append("個数").append(CSV_SEPERATOR)
.append("売り上げ").append(CSV_SEPERATOR);
bw.append(sb.toString());
bw.newLine();
for (DailyOutput dailyOutput : list) {
sb = new StringBuilder();
sb.append(dailyOutput.getTruckName()!=null?dailyOutput.getTruckName():"").append(CSV_SEPERATOR)
.append(dailyOutput.getCarriage()!=null?dailyOutput.getCarriage():"").append(CSV_SEPERATOR)
.append(dailyOutput.getDriverName()!=null?dailyOutput.getDriverName():"").append(CSV_SEPERATOR)
.append(dailyOutput.getStartDate()!=null?dailyOutput.getStartDate():"").append(CSV_SEPERATOR)
.append(dailyOutput.getDistance()!=null?dailyOutput.getDistance():"").append(CSV_SEPERATOR)
.append(dailyOutput.getCustomerName()!=null?dailyOutput.getCustomerName():"").append(CSV_SEPERATOR)
.append(dailyOutput.getCargoName()!=null?dailyOutput.getCargoName():"").append(CSV_SEPERATOR)
.append(dailyOutput.getNumber()!=null?dailyOutput.getNumber():"").append(CSV_SEPERATOR)
.append(dailyOutput.getAmount()!=null?dailyOutput.getAmount():"").append(CSV_SEPERATOR);
bw.append(sb.toString());
bw.newLine();
}
bw.flush();
} catch (Exception ex) {
log.error("Exception happened when write CSV for loan list.", ex);
}
}
};
Thread thread = new Thread(writer);
thread.start();
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.add("charset", "utf-8");
headers.add("Content-Disposition", "attachment;filename=\"" + contentDisposition.getFileName() + "\"");
Resource resource = new InputStreamResource(input);
return ResponseEntity.ok().headers(headers).contentType(MediaType.parseMediaType("application/x-msdownload")).body(resource);
}
window.open(encodeURI(SERVER_URL + "/templates/previewPdf?filePath=" + filePath + "&Authorization=Bearer " + localStorage.getItem("TOKEN")));
后台核心代码
public static void previewPdf(String filePath,HttpServletResponse response) {
try {
File tempFile = new File(filePath);
FileInputStream fis = new FileInputStream(tempFile);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
renderPdf(response,bytes,"pdf");
fis.close();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
public static void renderPdf(HttpServletResponse response, final byte[] bytes, final String filename) {
initResponseHeader(response, PDF_TYPE);
setFileDownloadHeader(response, filename, ".pdf");
if (null != bytes) {
try {
response.getOutputStream().write(bytes);
response.getOutputStream().flush();
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
}
private static HttpServletResponse initResponseHeader(HttpServletResponse response, final String contentType, final String... headers) {
String encoding = DEFAULT_ENCODING;
boolean noCache = DEFAULT_NOCACHE;
for (String header : headers) {
String headerName = StringUtils.substringBefore(header, ":");
String headerValue = StringUtils.substringAfter(header, ":");
if (StringUtils.equalsIgnoreCase(headerName, HEADER_ENCODING)) {
encoding = headerValue;
} else if (StringUtils.equalsIgnoreCase(headerName, HEADER_NOCACHE)) {
noCache = Boolean.parseBoolean(headerValue);
} else {
throw new IllegalArgumentException(headerName + "headerタイブ間違た");
}
}
String fullContentType = contentType + ";charset=" + encoding;
response.setContentType(fullContentType);
if (noCache) {
// Http 1.0 header
response.setDateHeader("Expires", 0);
response.addHeader("Pragma", "no-cache");
// Http 1.1 header
response.setHeader("Cache-Control", "no-cache");
}
return response;
}