Because the practice of previous projects is to obtain property by reflection, so the demo is also a reflection, I see many online articles are stored in a List <Map> in, I do not know what these two which is more appropriate point, or have What better way to no.
First introduced pom, lombok optional
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.13</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.13</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
entity
@Data @AllArgsConstructor public class Student { public String name; public int score; public int age; }
Service
import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class StudentService { public List<Student> getList(Student student, int index, int size) { Student student1 = new Student("张三", 90, 18); Student student2 = new Student("李四", 85, 17); Student student3 = new Student("王五", 70, 19); List<Student> list = new ArrayList<>(); list.add(student1); list.add(student2); list.add(student3); return list; } }
Controller
import lombok.Cleanup; import org.apache.poi.ss.usermodel.Workbook; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.List; @RestController public class StudentController { @Autowired StudentService studentService public; } catch (IOException e) { @RequestMapping ( "/ exportStudentExcel") public ResponseEntity <byte []> exportExcel (Student Student) { List <Student> List = studentService.getList (Student, 0, 10); // every time these lines only need to change String fileName = "student achievement statistics"; // a time need to change a few lines String [] getters = { "getName ", "getScore", "getAge"}; // each only need to change a few lines String [] headers = { "name", "score", "age"}; // only need to change every few lines Workbook wb = ExcelUtils.createWorkBook (list, getters , headers, student.getClass ()); // every time only a few lines need to change @Cleanup ByteArrayOutputStream ByteArrayOutputStream new new OS = (); the try { wb.write (OS); e.printStackTrace (); } Byte [] os.toByteArray content = (); HttpHeaders httpHeaders = new HttpHeaders(); try { fileName = URLEncoder.encode(fileName, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpHeaders.setContentDispositionFormData("attachment", fileName + ".xlsx"); return new ResponseEntity<byte[]>(content, httpHeaders, HttpStatus.OK); } }
ExcelUtils
ExcelUtils class {public / ** * create excel documents * * @param getters List of map of key array collection * @param headers excel column name * / public static Workbook createWorkBook (List List, String [] getters, String [] headers , Class clazz) { List <Method,> = getMethodsByStrs Methods (getters, clazz); // Create .xlsx workbook the workbook new new XSSFWorkbook WB = (); // Create a first sheet (page), and designated Sheet sheet = wb .createSheet ( "Sheet1"); . // manually set the column width to be expressed as a first parameter set of columns, the second column indicates the width parameter, n is the number of columns of pixels to be high. for (int I = 0 ; I <getters.length; I ++) { sheet.setColumnWidth ((Short) I, (Short) (35.7 * 200 is)); } // create a first row Row = sheet.createRow header (0); // create two cell formatting the CellStyle cellStyle1 wb.createCellStyle = (); the CellStyle cellStyle2 wb.createCellStyle = (); // create two Font Font font1 = wb.createFont (); // title Font Font font2 = wb.createFont (); // text font // title bold font1.setBoldweight (Font.BOLDWEIGHT_BOLD); // set two cell pattern setCellStype (cellStyle1 , font1); setCellStype (cellStyle2, font2); // set header for (int I = 0; I <headers.length; I ++) { the Cell Cell header.createCell = (I); cell.setCellValue (headers [I]) ; cell.setCellStyle (cellStyle1); } //设置data int headersNum = 1; for (int i = 0; i < list.size(); i++) { Row row = sheet.createRow(i + headersNum); for (int j = 0; j < methods.size(); j++) { try { Object invoke = methods.get(j).invoke(list.get(i)); if (invoke != null) { row.createCell(j).setCellValue(invoke.toString()); } } catch (Exception e) { e.printStackTrace(); } } } return wb; } private static void setCellStype(CellStyle cellStyle, Font font) { font.setFontHeightInPoints((short) 10); font.setColor(IndexedColors.BLACK.getIndex()); cellStyle.setFont(font); cellStyle.setBorderLeft(CellStyle.BORDER_THIN); cellStyle.setBorderRight(CellStyle.BORDER_THIN); cellStyle.setBorderTop(CellStyle.BORDER_THIN); cellStyle.setBorderBottom(CellStyle.BORDER_THIN); cellStyle.setAlignment(CellStyle.ALIGN_CENTER); } private static List<Method> getMethodsByStrs(String[] getters, Class clazz) { List<Method> list = new ArrayList<>(); for (String getter : getters) { try { list.add(clazz.getDeclaredMethod(getter)); } catch (NoSuchMethodException e) { e.printStackTrace(); } } return list; } }