后端:
controller:
@GetMapping(value = "/get-import-template")public void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {iUserService.problemTemplate(request, response);}
service:
void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception;
impl:
@Overridepublic void problemTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {String path = "file/user.xlsx";// 从类加载器获取资源InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path);// 设置响应头response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("产品运输阶段导入模版.xlsx", "UTF-8"));// 获取ServletOutputStreamServletOutputStream outputStream = response.getOutputStream();// 使用Apache POI的XSSFWorkbook将Excel文件写入输出流try (XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) {workbook.write(outputStream);} finally {// 确保输出流被关闭if (outputStream != null) {outputStream.flush();outputStream.close();}}}
前端:
html:
//批量导入<el-dialog :title="title" :visible.sync="importFormVisible" width="800px" :close-on-click-modal="false" :show-close="false"><div class="tip"><div class="bold">1</div><span class="btitle">下载模版</span></div><el-row :gutter="24"><div class="el-upload__tip text-center"><span>仅允许导入 xls、xlsx 格式文件;请按照要求填写模版文件</span><el-link:underline="false"style="font-size: 12px; vertical-align: baseline"type="primary"@click="importTemplate">下载导入模板</el-link></div></el-row><div style="padding: 8px 0; background: #f8fbff; margin-top: 10px"><div class="tip"><div class="bold">2</div><span class="btitle">导入文件</span></div></div><div style="padding: 8px 0; background: #f8fbff; margin-top: 10px"><div class="tip"><div class="bold">3</div><span class="btitle">删除</span></div><el-row :gutter="24"><el-inputv-model="importBatch"placeholder="请输入批次号"clearableclass="!w-240px"/><el-button @click="handleDelete">按批次号删除导入数据</el-button></el-row></div><div style="text-align:center;"><el-button type="primary" @click="saveUser">确定</el-button><el-button type="danger" @click="importFormVisible = false">取消</el-button></div></el-dialog>
js:
//下载导入模板importTemplate(){importTemplate().then((res) => {console.log(res, 'res')const blob = new Blob([res], { type: 'application/vnd.ms-excel' })// 创建 href 超链接,点击进行下载window.URL = window.URL || window.webkitURLconst href = URL.createObjectURL(blob)const downA = document.createElement('a')downA.href = hrefdownA.download = '组织架构用户导入模板.xlsx'downA.click()// 销毁超连接window.URL.revokeObjectURL(href)});},
实现效果: