java接口输出文件流
String filename = ""; //文件名称
InputStream in = null; //输入流
XSSFWorkbook workBook = null; //HSSFWorkbook读取97-2003格式 ,XSSFWorkbook读取2007-2013格式
OutputStream out = null; //输出流
//获取服务器Excel模板
String templatePath = request.getServletContext().getRealPath("/")+"export/template/指令统计详情模板.xlsx";
//重命名文件名
if(StringUtil.isNotEmpty(startTime) && StringUtil.isNotEmpty(endTime)) {
filename = "指令统计详情" + startTime + "-" + endTime+".xlsx";
}else {
filename = "指令统计详情" + System.currentTimeMillis() + ".xlsx";
}
// 读取Excel文档
File finalXlsxFile = new File(templatePath);
in = new FileInputStream(finalXlsxFile);
workBook = new XSSFWorkbook(in);
//样式1
XSSFCellStyle cellStyle = workBook.createCellStyle();
cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
//样式2
XSSFCellStyle cellStyle1 = workBook.createCellStyle();
cellStyle1.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
cellStyle1.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
//样式3
XSSFCellStyle cellStyle2 = workBook.createCellStyle();
cellStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
cellStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);//右边框
cellStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);//左边框
XSSFFont font1 = workBook.createFont();
font1.setFontHeightInPoints((short) 10);
font1.setFontName("微软雅黑");
cellStyle2.setFont(font1);//字体
// sheet 对应一个工作页
Sheet sheet = workBook.getSheetAt(0);
//从第三行开始
Row row = sheet.createRow(2);
//第一列
Cell cell = row.createCell(0);
//循环数据,datalist为数据list
for (int j = 0; j < dataList.size(); j++) {
// 创建一行:从第二行开始,跳过属性列
row = sheet.createRow(2+j);
//创建第一列,为序号列
cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue(j+1);
//创建第二列
cell = row.createCell(1);
cell.setCellStyle(cellStyle);
cell.setCellValue(map.get("superviseName"));
......
}
String fileName = filename;
fileName = URLEncoder.encode(fileName, "utf-8");
//获取输出流
OutputStream outputStream = response.getOutputStream();
response.reset();
//设置Http响应头告诉浏览器下载这个附件
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream; charset=utf-8");
workBook.write(outputStream);
outputStream.close(); //关闭输出流
outputStream.flush(); //清空输出流
Vue下载文件
/**
* 下载文件 用于excel导出
* @param url
* @param parameter
* @returns {*}
*/
export function downExcelFile(url, parameter) {
return request({
url: url,
data: parameter,
method: 'post',
responseType: 'blob'
})
}
downExcelFile(this.url.down, this.queryData)
.then(res => {
//获取文件名称
const filename = decodeURI(res.headers['content-disposition'].split(';')[1].split('=')[1]) || '.xls'
const blob = new Blob([res.data], {
type: 'application/octet-stream'
})
const url = window.URL.createObjectURL(blob)
const link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()
}
)