Hướng dẫn spring boot excel - khởi động mùa xuân excel
Chi tiết của & NBSP; Cập nhật lần cuối vào ngày 04 tháng 9 năm 2020 & NBSP; | & nbsp; & nbsp; in & nbsp; E-mail Last Updated on 04 September 2020 | Print Email Show
Xuất dữ liệu sang tài liệu Excel là một tính năng phổ biến của hầu hết mọi ứng dụng. Thông qua bài viết này, tôi rất vui mừng được chia sẻ với các bạn kinh nghiệm của tôi trong việc triển khai chức năng xuất Excel trong một ứng dụng khởi động mùa xuân với sự trợ giúp của thư viện Apache Poi Excel. Giả sử rằng chúng ta có một dự án khởi động mùa xuân hiện có bằng cách sử dụng Spring Data JPA và Hibernate để truy cập dữ liệu, Thymeleaf để hiển thị chế độ xem và MySQL làm cơ sở dữ liệu. Các ví dụ mã bên dưới trình bày cách truy xuất thông tin về người dùng từ cơ sở dữ liệu và tạo tệp Excel mà người dùng có thể tải xuống máy tính của họ. 1. Mã của các lớp thực thể và giao diện kho lưu trữChúng tôi có lớp thực thể người dùng & NBSP;User entity class that maps to the users table in the database, as shown below: package net.codejava; import java.util.*; import javax.persistence.*; @Entity @Table(name = "users") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String email; private String password; @Column(name = "full_name") private String fullName; private boolean enabled; @ManyToMany(cascade = CascadeType.PERSIST, fetch = FetchType.EAGER) @JoinTable( name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id") ) private Set Và Vai trò & NBSP; lớp thực thể ánh xạ vào bảng Vai trò trong cơ sở dữ liệu:Role entity class that maps to the roles table in the database: package net.codejava; import javax.persistence.*; @Entity @Table(name = "roles") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; private String description; // constructors, getter and setters are not shown for brevity } Các trường sẽ được bao gồm trong tài liệu Excel được tạo là: ID người dùng, e-mail, tên đầy đủ, vai trò và được bật. Và mã của các giao diện kho lưu trữ tương ứng trông như thế này: package net.codejava; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository Đây là những kho lưu trữ đơn giản, điển hình theo yêu cầu của Spring Data JPA. 2. Khai thác phụ thuộc cho Thư viện ExcelĐể tạo tệp Excel, chúng ta cần sử dụng thư viện bên ngoài và Apache POI là một trong những tệp phổ biến nhất. Vì vậy, chúng tôi cần khai báo sự phụ thuộc sau đây để sử dụng Apache POI cho Excel trong tệp dự án Maven,:
3. Mã cho lớp dịch vụTrong lớp dịch vụ, chúng tôi có thể có lớp người dùng & NBSP; như sau:UserServices class as follows: package net.codejava; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; @Service @Transactional public class UserServices { @Autowired private UserRepository repo; public List Như bạn có thể thấy, phương thức listall () giao cho phương thức gọi đến phương thức findall () của giao diện người dùng, được thực hiện bởi spring Data jpa (mở rộng từ jparepository). Phương thức Listall () sẽ được gọi để lấy dữ liệu về người dùng từ cơ sở dữ liệu.listAll() method delegates the call to the findAll() method of the UserRepository interface, which is implemented by Spring Data JPA (extended from JpaRepository). The listAll() method will be invoked to get data about users from the database. 4. Code Excel ClassTiếp theo, mã một lớp riêng biệt chịu trách nhiệm tạo tài liệu Excel dựa trên đầu vào là A & NBSP; Danh sách & NBSP; Bộ sưu tập & NBSP; Người dùng & NBSP; đối tượng, như được hiển thị bên dưới:List collection of User objects, as shown below: package net.codejava; import java.io.IOException; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class UserExcelExporter { private XSSFWorkbook workbook; private XSSFSheet sheet; private List Lớp này sẽ tạo một tài liệu Excel với một tờ chứa hàng tiêu đề và hàng cho dữ liệu. Hàng tiêu đề bao gồm các cột sau: ID người dùng, e-mail, tên đầy đủ, vai trò và được bật. Hãy chú ý đến phương thức & nbsp; export () & nbsp; lấy & nbsp; httpservletrespone & nbsp; làm đối số, bởi vì nó sẽ viết nội dung của tệp excel vào luồng đầu ra của phản hồi, vì vậy các máy khách (trình duyệt web) sẽ có thể Tải xuống tệp Excel đã xuất.export() method that takes an HttpServletRespone as the argument, because it will write the content of the Excel file into the output stream of the response, so the clients (web browsers) will be able to download the exported Excel file. 5. Phương pháp xử lý mã trong lớp bộ điều khiểnTiếp theo, thực hiện phương thức xử lý trong lớp Bộ điều khiển MVC Spring - UserControll - như sau:UserController – as follows: package net.codejava; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class UserController { @Autowired private UserServices service; @GetMapping("/users/export/excel") public void exportToExcel(HttpServletResponse response) throws IOException { response.setContentType("application/octet-stream"); DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); String currentDateTime = dateFormatter.format(new Date()); String headerKey = "Content-Disposition"; String headerValue = "attachment; filename=users_" + currentDateTime + ".xlsx"; response.setHeader(headerKey, headerValue); List Như bạn có thể thấy phương thức ExportToExcel () sẽ phục vụ HTTP, hãy nhận yêu cầu với URI/User/Export/Excel. Nó sẽ sử dụng lớp người dùng để lấy dữ liệu của người dùng từ cơ sở dữ liệu và sử dụng lớp UserExcelExporter để viết tài liệu Excel vào phản hồi.exportToExcel() method will serve HTTP GET request with the URI /users/export/excel. It will use the UserServices class to get data of users from the database, and use the UserExcelExporter class to write an Excel document to the response. Ngoài ra, tên thông báo của tệp Excel được tạo được thêm vào thời gian ngày hiện tại, giúp người dùng dễ dàng theo dõi nhiều phiên bản của các tệp được tải xuống. 6. Thêm liên kết Export Excel trong trang xemChúng tôi sử dụng HTML và Thymeleaf để tạo một siêu liên kết cho phép người dùng nhấp để xuất dữ liệu để xuất sắc như sau: Export to Excel 7. Kiểm tra xuất và tải xuống tệp ExcelNhấp vào Exprink Export sang Excel, ứng dụng Spring Boot sẽ tạo tệp Excel và trình duyệt sẽ tự động tải xuống tệp đó. Tên tệp là một cái gì đó như thế này: user_2020-09-02_11-30-06.xlsx. Mở tệp này bằng ứng dụng Microsoft Excel, bạn sẽ thấy màn hình sau:users_2020-09-02_11-30-06.xlsx. Open this file using Microsoft Excel application, you would see the following screen: Sự kết luậnCho đến nay bạn đã học được cách mã hóa chức năng xuất Excel cho một ứng dụng web khởi động mùa xuân. Bạn thấy, JPA dữ liệu Spring giúp dễ dàng lấy dữ liệu từ cơ sở dữ liệu và Apache POI giúp dễ dàng tạo tài liệu tương thích với định dạng Microsoft Excel. Đối với phiên bản video của hướng dẫn này, hãy xem video dưới đây: Hướng dẫn liên quan:
Hướng dẫn khởi động mùa xuân khác:
Thông tin về các Tác giả:Thêm bình luận |