poi导出excel

依赖:

org.apache.poi
poi
4.0.1


org.apache.poi
poi-ooxml
4.0.1


org.apache.poi
poi-ooxml-schemas
4.0.1

@Api(description = “导出excel”)
@RestController
@Log4j2
@RequestMapping(“export”)
public class PoiController {
@ApiOperation(“导出”)
@RequestMapping( method = RequestMethod.GET)
public MelotResult index(HttpServletResponse response) throws IOException {
List studentList = getStudentList();
//1.创建workbook工作簿
Workbook wb = new XSSFWorkbook();
createFirstRow(wb,studentList);
response.setContentType(“application/vnd.ms-excel;chartset=utf-8”);
String fileName = URLEncoder.encode(“汇总”, “UTF8”);
response.setHeader(“Content-Disposition”, “attachment;filename=”+fileName + “.xlsx”);
ServletOutputStream out=response.getOutputStream();
wb.write(out);
out.flush();
out.close();
return new MelotResult<>("");
}
public List getStudentList(){
Student student = new Student();
student.setId(1L);
student.setAge(10);
student.setName(“one”);

    Student student1 = new Student();
    student1.setId(2L);
    student1.setAge(11);
    student1.setName("two");

    Student student2 = new Student();
    student2.setId(2L);
    student2.setAge(11);
    student2.setName("two");
    ArrayList list = Lists.newArrayList();
    list.add(student);
    list.add(student1);
    list.add(student2);
    return  list;

}
public  void createFirstRow(Workbook wb, List studentList ){
    //2.创建表单Sheet
    Sheet sheet = wb.createSheet("sheet1");

    //合并单元格
    CellRangeAddress region =new CellRangeAddress(0, 0, 0, 2);
    sheet.addMergedRegion(region);

    CellStyle cellStyle = wb.createCellStyle();

    for (int i =0;i<20;i++){

        sheet.setColumnWidth(i, 5000);//设置列的宽度是31个字符宽度
    }

    Row row = sheet.createRow(0);
    row.setHeightInPoints(50);//设置行的高度是50个点
    //创建单元格样式对象
    Cell cell = row.createCell(0);
    cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
    cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
    //设置单元格样式
    cell.setCellStyle(cellStyle);



    cell.setCellValue("学生明细表");

    Row row1 = sheet.createRow(1);
    Cell cell1 = row1.createCell(0);
    cell1.setCellValue("id");

    Cell cell2 = row1.createCell(1);
    cell2.setCellValue("年龄");

    Cell cell3 = row1.createCell(2);
    cell3.setCellValue("姓名");

    int rowNum = 2;
    for (Student student : studentList) {
        Row sheetRow= sheet.createRow(rowNum);
        Cell cell4 = sheetRow.createCell(0);
        cell4.setCellValue(student.getId());

        Cell cell5 = sheetRow.createCell(1);
        cell5.setCellValue(student.getAge());

        Cell cell6 = sheetRow.createCell(2);
        cell6.setCellValue(student.getName());

        rowNum++;
    }
}

}

你可能感兴趣的:(java)