1.添加maven
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
2.连接数据库
3.创建pojo、service、serviceImpl
4.编写sql语句
5编写controller(重要部分)
@RequestMapping("/testExcel") public void testExcel()throws Exception{ // 建立一个工作表--相当于一个数据库 Workbook book = new HSSFWorkbook(); Sheet sheet1 =book.createSheet("这个是表名"); // 行 Row row =sheet1.createRow(0); // 单元格 Cell cell = row.createCell(3); // 写入数据 cell.setCellValue("这个是表头"); List<People> list = peopleServiceImpl.getList(); for (int i=1;i<list.size;i++){ Row row1 = sheet1.createRow(i); TPersonClue tPersonClue = list.get(i-1); /** * 为单元格写入值,从0开始 */ row1.createCell(0).setCellValue(tPersonClue.getId()); row1.createCell(1).setCellValue(tPersonClue.getName()); row1.createCell(2).setCellValue(tPersonClue.getAge()); row1.createCell(3).setCellValue(tPersonClue.getSex()); } book.write( new FileOutputStream("D:\\java\\excel\\位置.xls")); }