- Sơ lược
Một tính năng phổ biến của các ứng dụng web là khả năng tải xuống các tệp.Trong hướng dẫn này, chúng tôi sẽ trình bày một ví dụ đơn giản về việc tạo tệp có thể tải xuống và phục vụ nó từ ứng dụng Java Servlet -
- Điều kiện tiên quyết: Trong bài này chúng ta cần sử dụng thư viện.
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency> -
- Đặt vấn đề : Hãy giả định bạn đang có thông tin nào đó trong Database, hoặc một List dữ liệu đang cần xuất ra dạng excel để phục vụ cho các mục đích khác nhau. Vd: In ra thông tin các nhân viên có lương >=9.000.000 vnd.
-
- Hướng giải quyết vấn đề: Đầu tiên chúng ta cần có danh sách các nhân viên phù hợp với mức lương > 9.000.000. Sau đó danh sách này sẽ được xử lý để chuyển dổi dữ liệu sang dạng danh sách excel . Tôi đã xử lý như thế này.
-
- Thực hiện
- Tạo lớp Employee
@Data @NoArgsConstructor @AllArgsConstructor public class Employee { private String name; private Date birth; private double salary; }
-
- Xây dựng XlsxView trong spring.
package com.trungthuc.Excel; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.ss.usermodel.*; import org.springframework.web.servlet.view.document.AbstractXlsxView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.List; import java.util.Map; public class Excel extends AbstractXlsxView { private String [] columName={"name","birth","salary"}; @Override protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception { String exelName ="employee.xlsx"; // tên file excel sẽ dk tải xuống. Sheet sheet =workbook.createSheet("Employee"); CreationHelper creationHelper =workbook.getCreationHelper(); // font áp dụng cho row header (dòng tiêu đề ) Font fontHeader =workbook.createFont(); fontHeader.setBold(true); fontHeader.setColor(IndexedColors.BLUE.getIndex()); fontHeader.setFontHeightInPoints((short) 14); fontHeader.setCharSet(HSSFFont.ANSI_CHARSET); // style áp dụng cho row header (dòng tiêu đề ) CellStyle cellStyle =workbook.createCellStyle(); cellStyle.setFont(fontHeader); cellStyle.setLocked(true); // tạo mới row header (dòng tiêu đề ) vd:(name,tuổi , ngày sinh Row headerRow = sheet.createRow(0); // gán giá trị cho các cột đầu tiên (row header) for (int i=0;i<columName.length;i++){ Cell cell =headerRow.createCell(i); cell.getStringCellValue().getBytes(Charset.forName("UTF-8")); cell.setCellValue(columName[i]); cell.setCellStyle(cellStyle); } // cell style cho các dòng chứ thông tin CellStyle cellStyleF=workbook.createCellStyle(); cellStyleF.setDataFormat(creationHelper.createDataFormat().getFormat("dd-MM-yyyy")); List<Employee> list = (List<Employee>) model.get("employes"); // employes được get ra từ controller int row=1; for (Employee es: list){ Row epe = sheet.createRow(row++); epe.createCell(0).setCellValue(es.getName()); Cell dateOfBirthCell = epe.createCell(1); dateOfBirthCell.getStringCellValue().getBytes(Charset.forName("UTF-8")); dateOfBirthCell.setCellValue(es.getBirth()); dateOfBirthCell.setCellStyle(cellStyleF); epe.createCell(2).setCellValue(es.getSalary()); } for(int i = 0; i < columName.length; i++) { // tự động thay đổi cho vừa kích thước cho các ô dữ liệu sheet.autoSizeColumn(i); } try { // gửi kèm file thông qua response response.setHeader("Content-Disposition", "attachement; filename=\"" + java.net.URLEncoder.encode(exelName, "UTF-8") + "\";charset=\"UTF-8\""); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } }
-
- Xây dựng controller
-
-
package com.trungthuc.Excel; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.View; import java.util.ArrayList; import java.util.Date; import java.util.List; @Controller public class ControllerEx { public static List<Employee> getAll=new ArrayList<>(); // mảng dữ liệu giả định public static void fetchD() { for (int i=1;i<=100;i++){ getAll.add(new Employee("data"+i,new Date(),(i+1)*2)); System.out.println("i = " + i); } } // dường dẫn đễ tải file @GetMapping(value = "/dowload") public View dowload(Model mm){ fetchD(); mm.addAttribute("employes",getAll); return new Excel(); } }
-
-
-
- Giải thích
String exelName =“employee.xlsx”;
// tên file excel sẽ dk tải xuống.
Sheet sheet =workbook.createSheet(“Employee”);
CreationHelper creationHelper =workbook.getCreationHelper();
// style áp dụng cho row header (dòng tiêu đề )
CellStyle cellStyle =workbook.createCellStyle();
cellStyle.setFont(fontHeader);
cellStyle.setLocked(true);
// gán giá trị cho các cột đầu tiên (row header)
for (int i=0;i<columName.length;i++){
Cell cell =headerRow.createCell(i);
cell.getStringCellValue().getBytes(Charset.forName(“UTF-8”));
cell.setCellValue(columName[i]);
cell.setCellStyle(cellStyle);
}
// cell style cho các dòng chứ thông tin
CellStyle cellStyleF=workbook.createCellStyle();
cellStyleF.setDataFormat(creationHelper.createDataFormat().getFormat(“dd-MM-yyyy”)); -
- Cách truyền dữ liệu từ controller và AbstractXslxView
-
- Tạo lớp Employee
- Test kết quả: LÊN TRÌNH DUYỆT VÀ gõ http://localhost:8080/dowload để xem kết quả.
-
- Tổng kết: Tải xuống tệp từ Servlet trở thành một quy trình đơn giản. Sử dụng các luồng cho phép chúng tôi phân phát dữ liệu dưới dạng byte và Loại phương tiện thông báo cho trình duyệt máy khách loại dữ liệu mong đợi.Trình duyệt xác định cách xử lý phản hồi, tuy nhiên, có rất nhiều cách để làm công việc này tùy vào yêu cầu của dự án và tech được sử dụng.
-
Theo dõi
Đăng nhập
0 Góp ý