Download.vue
<script>
export default {
data() {
return {
userId: '',
form: {
name: '',
gender: '',
email: '',
},
list: [
{
startTime: '',
endTime: '',
text: '',
}
],
};
},
activated: function () {
this.userId = sessionStorage.getItem("userId");
},
methods: {
async download() {
let url = "/v1/test/downloadExcel";
await this.$http.post(url, {
info: this.form,
list: this.list,
}, { responseType: 'blob' })
.then((response) => {
const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
const url = URL.createObjectURL(blob);
// 创建一个下载链接并模拟点击
const link = document.createElement('a');
link.href = url;
link.download = this.form.name + '.xlsx';
link.click();
// 释放创建的 URL 对象
URL.revokeObjectURL(url);
})
.catch((err) => { });
},
},
};
</script>
PlanControllor.java
@RestController
@RequestMapping("/v1/test")
public class PlanController {
@Autowired
private DownloadService downloadService;
@PostMapping("/downloadExcel")
public void downloadExcel(@RequestBody InfoInputVO inputVO, HttpServletResponse response) {
// excel下载
downloadService.downloadExcel(inputVO, response);
}
}
DownloadServiceImpl.java
@Service
public class DownloadServiceImpl implements DownloadService {
@Transactional
@Override
public void downloadExcel(InfoInputVO inputVO, HttpServletResponse response) {
// 取得下载内容
Info info = inputVO.getInfo();
List<Text> list = inputVO.getList();
// 获取模板
ClassPathResource classPathResource = new ClassPathResource("/templates/template.xlsx");
// 输入流
InputStream inputStream = null;
// 输出流
ServletOutputStream outputStream = null;
// Excel对象
ExcelWriter excelWriter = null;
try {
// 输入流
inputStream = classPathResource.getInputStream();
response.setContentType("application/vnd.ms-excel");
response.setCharacterEncoding("utf-8");
String fileName = URLEncoder.encode("excel", "UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
outputStream = response.getOutputStream();
excelWriter = EasyExcel.write(outputStream).registerWriteHandler(writeHandler).withTemplate(inputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
excelWriter.fill(info, writeSheet);
excelWriter.fill(list, writeSheet);
excelWriter.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (excelWriter != null) {
excelWriter.finish();
}
//关闭流
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}