1.引入依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15</version> </dependency>数据库表:
2.代码:
row:行
cell:单元格
@RequestMapping("/exportExcel") @ResponseBody public HSSFWorkbook exportExcel(HttpServletResponse response){ log.info("创建新的Excel工作薄"); HSSFWorkbook workBook = new HSSFWorkbook(); HSSFSheet sheet = workBook.createSheet("人员信息"); //创建第一行,做表头 HSSFRow row = sheet.createRow((short)0); //第一行 单位 HSSFCell cell = row.createCell(0); List<String> list = personService.getCols(); for(int i=0;i<list.size();i++){ //表头 cell=row.createCell(i); cell.setCellValue(list.get(i)); } List<Person> personList = personService.listPersons(); for(int i=0;i<personList.size();i++){ row = sheet.createRow(i+1); cell = row.createCell(0); cell.setCellValue(personList.get(i).getId()); cell = row.createCell(1); cell.setCellValue(personList.get(i).getName()); cell = row.createCell(2); cell.setCellValue(personList.get(i).getCountry()); } try { // 设置请求 response.setContentType("application/application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode( "人员信息.xls", "UTF-8")); //写入 workBook.write(response.getOutputStream()); response.getOutputStream().flush(); response.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); } return workBook; }表字段作为第一行表头:查询表字段名sql语句 select column_name from information_schema.columns where table_name='表名'
导出: