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

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 roles = new HashSet[];

	// constructors, getter and setters are not shown for brevity
}

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 {
	
}


public interface RoleRepository extends CrudRepository {
	
}

Đâ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,:

	org.apache.poi
	poi-ooxml
	4.1.0
  

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 listAll[] {
		return repo.findAll[Sort.by["email"].ascending[]];
	}
	
}

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 Class

Tiế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 listUsers;
	
	public UserExcelExporter[List listUsers] {
		this.listUsers = listUsers;
		workbook = new XSSFWorkbook[];
	}


	private void writeHeaderLine[] {
		sheet = workbook.createSheet["Users"];
		
		Row row = sheet.createRow[0];
		
		CellStyle style = workbook.createCellStyle[];
		XSSFFont font = workbook.createFont[];
		font.setBold[true];
		font.setFontHeight[16];
		style.setFont[font];
		
		createCell[row, 0, "User ID", style];		
		createCell[row, 1, "E-mail", style];		
		createCell[row, 2, "Full Name", style];		
		createCell[row, 3, "Roles", style];
		createCell[row, 4, "Enabled", style];
		
	}
	
	private void createCell[Row row, int columnCount, Object value, CellStyle style] {
		sheet.autoSizeColumn[columnCount];
		Cell cell = row.createCell[columnCount];
		if [value instanceof Integer] {
			cell.setCellValue[[Integer] value];
		} else if [value instanceof Boolean] {
			cell.setCellValue[[Boolean] value]; 
		}else {
			cell.setCellValue[[String] value];
		}
		cell.setCellStyle[style];
	}
	
	private void writeDataLines[] {
		int rowCount = 1;

		CellStyle style = workbook.createCellStyle[];
		XSSFFont font = workbook.createFont[];
		font.setFontHeight[14];
		style.setFont[font];
				
		for [User user : listUsers] {
			Row row = sheet.createRow[rowCount++];
			int columnCount = 0;
			
			createCell[row, columnCount++, user.getId[], style];
			createCell[row, columnCount++, user.getEmail[], style];
			createCell[row, columnCount++, user.getFullName[], style];
			createCell[row, columnCount++, user.getRoles[].toString[], style];
			createCell[row, columnCount++, user.isEnabled[], style];
			
		}
	}
	
	public void export[HttpServletResponse response] throws IOException {
		writeHeaderLine[];
		writeDataLines[];
		
		ServletOutputStream outputStream = response.getOutputStream[];
		workbook.write[outputStream];
		workbook.close[];
		
		outputStream.close[];
		
	}
}

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ển

Tiế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 listUsers = service.listAll[];
		
		UserExcelExporter excelExporter = new UserExcelExporter[listUsers];
		
		excelExporter.export[response];		
	}	

}

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 xem

Chú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 Excel

Nhấ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ận

Cho đế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:

  • Cách viết các tệp Excel trong Java bằng Apache POI
  • Ví dụ về mã Java để xuất từ ​​cơ sở dữ liệu sang tệp Excel
  • Cách đọc các tệp Excel trong Java bằng Apache POI
  • Ví dụ về mã Java để nhập dữ liệu từ excel vào cơ sở dữ liệu

Hướng dẫn khởi động mùa xuân khác:

  • Dữ liệu xuất khẩu khởi động mùa xuân sang ví dụ CSV
  • Dữ liệu xuất khẩu khởi động mùa xuân sang ví dụ PDF
  • Mùa xuân khởi động xin chào thế giới ví dụ
  • Khởi động tự động khởi động Spring bằng cách sử dụng Spring Boot DevTools
  • Hướng dẫn xử lý biểu mẫu khởi động mùa xuân với các thẻ mẫu lò xo và JSP
  • Cách tạo ứng dụng web khởi động Spring [MVC Spring với JSP/Thymeleaf]
  • Mùa xuân khởi động - Dữ liệu mùa xuân JPA - Ví dụ MySQL
  • Mùa xuân khởi động xin chào hướng dẫn dịch vụ web yên tĩnh thế giới
  • Cách sử dụng JDBC với khởi động lò xo
  • Ứng dụng web khởi động mùa xuân với JDBC - Thymeleaf - Oracle
  • Spring Boot Restful Crud API API Ví dụ với cơ sở dữ liệu MySQL
  • Cách đóng gói ứng dụng khởi động mùa xuân cho Jar và War
  • Xác thực bảo mật khởi động mùa xuân với JPA, Hibernate và MySQL
  • Các ví dụ phân loại và phân loại dữ liệu mùa xuân
  • Hướng dẫn xử lý lỗi khởi động mùa xuân


Thông tin về các Tác giả:

Nam Ha Minh được lập trình viên Java được chứng nhận [SCJP và SCWCD].Anh bắt đầu lập trình với Java vào thời Java 1.4 và đã yêu Java kể từ đó.Kết bạn với anh ấy trên Facebook và xem video Java của anh ấy là YouTube.

Thêm bình luận

Bài Viết Liên Quan

Chủ Đề