后端:
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)});},
實現效果: