導出數據我用的是poi導出excel文件在pom文件中引入
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.17</version> </dependency> <!-- poi-ooxml XSSF is our port of the Microsoft Excel XML (2007+) file format (OOXML) to pure Java --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.17</version> </dependency>
獲取任意表名和表中的字段參考文章
Mybatis 動態傳sql可以查詢表名,任意表名,不固定字段的個數返回未定義的類型以及增刪改
之后再controller層引用
@ApiOperation(value = "導出任意表中的數據", notes = "") @GetMapping("/executeTableInfo") @SystemControllerLog(title = "導出數據",businessType = BusinessType.EXPORT) public void executeTableInfo(@RequestParam("tableName")String tableName,HttpServletRequest request, HttpServletResponse response) throws IOException { List<Map<String, String>> maps = managerTableService.executeTableInfo(tableName); List<String> tableCloumName = managerTableService.getTableCloumName("'"+tableName+"'"); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet=workbook.createSheet(tableName); //設置導出的文件的名字 String filename=tableName+".xls"; //創建表頭 HSSFRow tablerow = sheet.createRow(0); //循環添加表頭數據 for (int i = 0; i < tableCloumName.size(); i++) { HSSFCell cell=tablerow.createCell(i); HSSFRichTextString text=new HSSFRichTextString(tableCloumName.get(i)); cell.setCellValue(text); } for (int i = 0; i < maps.size(); i++) { // 一個List對象是一個Map,一行數據,一個Map對象對應一行里的一條數據 Map tableMap = maps.get(i); //表頭是第0行,所以從第一行開始創建 Row row = sheet.createRow(i + 1); //循環創建單元格 for (int j = 0; j < tableCloumName.size(); j++) { //獲取指定字段的值,判斷是否為空 Object object=tableMap.get(tableCloumName.get(j)); String val=""; if(object!=null){ val=object.toString(); } row.createCell(j).setCellValue(val); } } response.setContentType("application/octet-stream"); response.setHeader("Content-disposition", "attachment;filename="+filename); try { response.flushBuffer(); workbook.write(response.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } }
這么寫就可以導出任何表中的數據,親測可行
