一、后端
- 导入依赖
language-xml1 2 3 4 5
| <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency>
|
- controller层
其中@RequestParam String moveNo
是前端传入的参数,而HttpServletResponse response
不是,前者可以没有,后者一定要有。
language-java1 2 3 4 5 6 7
| @GetMapping("/yourControllerApi") public AjaxResult exportData(@RequestParam String moveNo, HttpServletResponse response){ System.out.println(moveNo); System.out.println(response); return stockMgntService.exportData(moveNo, response); }
|
- service层
language-java1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| @Service public class StockMgntServiceImpl implements StockMgntService { @Override public AjaxResult exportData(String moveNo, HttpServletResponse response) { //这里是从后台resources文件夹下读取一个excel模板 ClassPathResource resource = new ClassPathResource("template/模板.xlsx"); try(InputStream fis = resource.getInputStream(); Workbook workbook = WorkbookFactory.create(fis); ServletOutputStream os = response.getOutputStream() ){ //这块写入你的数据 //往第一个sheet的第一行的第2列和第5列写入数据 Sheet sheet = workbook.getSheetAt(0); sheet.getRow(0).getCell(1, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellValue("test"); sheet.getRow(0).getCell(5, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK).setCellValue("test"); /*......你的操作......*/ //这块开始配置传输 response.setCharacterEncoding("UTF-8"); response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=template.xlsx"); response.flushBuffer(); workbook.write(os); os.flush(); os.close(); }catch (IOException e) { throw new RuntimeException(e); } return null; } }
|
二、前端
axios
向对应api发送请求并携带参数,然后使用Blob
来接收后端的OutputStream输出流并保存下载保存到本地浏览器。
language-html1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| <template> <el-button type="primary" @click="downloadData" size="small" plain>模板下载</el-button> </template>
<script setup> const downloadData = () => { console.log(queryParams.moveNo) axios({ url: '/yourControllerApi', method: 'get', params: { moveNo:'0000212132142'}, responseType: "blob" }).then(rp=>{ console.log(rp) const blob = new Blob([rp], { type: 'application/vnd.ms-excel'}); let link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.setAttribute('download', '模板下载.xlsx'); link.click(); link = null; }); } </script>
|