Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Cách đọc tệp excel trong khởi động mùa xuân

  • Cách đọc tệp excel trong khởi động mùa xuân

Vui lòng nhấp vào liên kết sau để tải xuống dự án mẫu.

Đọc tệp excel trong dự án mẫu khởi động mùa xuân (483 lượt tải xuống)

Cách đọc tệp excel trong khởi động mùa xuân

Vui lòng làm theo các bước sau để biết cách đọc tệp Excel trong Spring Boot 1) Đầu tiên tạo một dự án Maven đơn giản và khởi động khởi động Spring Boot và Apache POI được hiển thị bên dưới
1)First create a simple maven project and spring boot starter and apache poi dependency which is shown below

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân


	org.springframework.boot
	spring-boot-starter-web

		

	org.apache.poi
	poi
    4.1.2

		

    org.apache.poi
    poi-ooxml
    4.1.2

2) Bây giờ hãy tạo RestControll để đọc tệp Excel được hiển thị bên dưới

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i

3) Bây giờ hãy chạy ứng dụng khởi động mùa xuân của bạn

4) Bây giờ chúng tôi sẽ sử dụng dữ liệu Excel sau đây cho mục đích kiểm tra

5) Bây giờ mở người đưa thư và tạo yêu cầu POST được hiển thị bên dưới

6) Khi bạn nhấp vào Gửi, bạn sẽ thấy loại dữ liệu sau trên bảng điều khiển được hiển thị bên dưới

Thường xuyên đặt câu hỏi

1) Cách nhận số lượng lớn mà không cần số mũ bằng cách sử dụng Apache Poi trong Spring Boot


Trả lời: DataFormatter DataFormatter = new DataFormatter (); dataFormatter.formatCellValue ();
DataFormatter dataformatter = new DataFormatter();
dataformatter.formatCellValue();

Tệp Excel là định dạng tệp bảng tính do Microsoft tạo để sử dụng với Microsoft Excel. Bạn có thể sử dụng tệp để tạo, xem, chỉnh sửa, phân tích dữ liệu, biểu đồ, ngân sách và nhiều hơn nữa. Trong hướng dẫn này, tôi sẽ chỉ cho bạn cách tải lên/nhập dữ liệu tệp Excel vào cơ sở dữ liệu MySQL bằng Spring Boot & Apache POI, sau đó xuất API REST để trả lại tệp Excel từ bảng cơ sở dữ liệu.

Bài viết liên quan: - Ví dụ tải lên tệp Multiart Spring Boot
– Spring Boot Multipart File upload example
– How to upload multiple files in Java Spring Boot
– Upload/Import CSV file to MySQL Database in Spring Boot
– Spring Boot: Download Excel file from MySQL database table

Triển khai: - Triển khai ứng dụng khởi động mùa xuân trên AWS - Beanstalk đàn hồi - Docker Compose: Spring Boot và MySQL Ví dụ
– Deploy Spring Boot App on AWS – Elastic Beanstalk
– Docker Compose: Spring Boot and MySQL example

Nội dung

  • API REST Boot Boot để tải lên các tệp excel
  • API REST BOOT REST TRẢ LẠI Tệp ​​Excel
  • Công nghệ
  • Cấu trúc dự án
  • Thiết lập dự án tải lên tệp excel khởi động mùa xuân
  • Định cấu hình DataSource Spring, JPA, Hibernate
  • Xác định mô hình dữ liệu
  • Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu
  • Thực hiện Lớp trợ giúp đọc/Viết Excel
  • Tạo dịch vụ tệp Excel
  • Xác định thông báo phản hồi
  • Tạo bộ điều khiển để tải lên các tệp excel
  • Định cấu hình Tệp nhiều phần cho Servlet
  • Xử lý ngoại lệ tải lên tệp
  • Chạy & Kiểm tra
  • Sự kết luận
  • Đọc thêm
  • Mã nguồn

API REST Boot Boot để tải lên các tệp excel

API REST BOOT REST TRẢ LẠI Tệp ​​Excel.xlsx file that contains Tutorial data as following:

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Công nghệ

  • Cấu trúc dự án
  • Thiết lập dự án tải lên tệp excel khởi động mùa xuân
  • Định cấu hình DataSource Spring, JPA, Hibernate

Xác định mô hình dữ liệu

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

API REST BOOT REST TRẢ LẠI Tệp ​​Excel

Công nghệtutorials.xlsx that contains data in MySQL table:

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Cấu trúc dự án
You need to set the HTTP header:

"Content-disposition" : "attachment; filename=[yourFileName]" 
"Content-Type" : "application/vnd.ms-excel"

Thiết lập dự án tải lên tệp excel khởi động mùa xuân
Spring Boot: Download Excel file from MySQL database table

Định cấu hình DataSource Spring, JPA, Hibernate

Xác định mô hình dữ liệuTạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệuThực hiện Lớp trợ giúp đọc/Viết Excel
Tạo dịch vụ tệp ExcelXác định thông báo phản hồiTạo bộ điều khiển để tải lên các tệp excel
Định cấu hình Tệp nhiều phần cho ServletXử lý ngoại lệ tải lên tệpChạy & Kiểm tra
Định cấu hình Tệp nhiều phần cho ServletXử lý ngoại lệ tải lên tệpChạy & Kiểm tra

Công nghệ

  • Cấu trúc dự án
  • Thiết lập dự án tải lên tệp excel khởi động mùa xuân
  • Định cấu hình DataSource Spring, JPA, Hibernate
  • Xác định mô hình dữ liệu

Cấu trúc dự án

Thiết lập dự án tải lên tệp excel khởi động mùa xuân

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Định cấu hình DataSource Spring, JPA, Hibernate

Xác định mô hình dữ liệututorials.

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i8 is an interface that
extends 
package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i9 for persisting data.

Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu

Thực hiện Lớp trợ giúp đọc/Viết Excel

Tạo dịch vụ tệp Excel

Xác định thông báo phản hồi
– pom.xml for Spring Boot, MySQL connector, Apache POI dependencies.

Thiết lập dự án tải lên tệp excel khởi động mùa xuân

Định cấu hình DataSource Spring, JPA, Hibernate

Xác định mô hình dữ liệupom.xml and add these dependencies:


	org.springframework.boot
	spring-boot-starter-data-jpa



	org.springframework.boot
	spring-boot-starter-web



	org.apache.poi
	poi-ooxml
	4.1.2



	mysql
	mysql-connector-java
	runtime

Định cấu hình DataSource Spring, JPA, Hibernate

Xác định mô hình dữ liệusrc/main/resources folder, open application.properties and write these lines.

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
  • Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu
  • Thực hiện Lớp trợ giúp đọc/Viết Excel
  • Tạo dịch vụ tệp Excel

Xác định mô hình dữ liệu

Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu
In model package, we define

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i7 class.

model/Tutorial.java

package com.bezkoder.spring.files.excel.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tutorials")
public class Tutorial {

  @Id
  @Column(name = "id")
  private long id;

  @Column(name = "title")
  private String title;

  @Column(name = "description")
  private String description;

  @Column(name = "published")
  private boolean published;

  public Tutorial() {

  }

  public Tutorial(String title, String description, boolean published) {
    this.title = title;
    this.description = description;
    this.published = published;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public boolean isPublished() {
    return published;
  }

  public void setPublished(boolean isPublished) {
    this.published = isPublished;
  }

  @Override
  public String toString() {
    return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
  }
}

Thực hiện Lớp trợ giúp đọc/Viết Excel


	org.springframework.boot
	spring-boot-starter-data-jpa



	org.springframework.boot
	spring-boot-starter-web



	org.apache.poi
	poi-ooxml
	4.1.2



	mysql
	mysql-connector-java
	runtime

4 annotation provides the table that maps this entity.

	org.springframework.boot
	spring-boot-starter-data-jpa



	org.springframework.boot
	spring-boot-starter-web



	org.apache.poi
	poi-ooxml
	4.1.2



	mysql
	mysql-connector-java
	runtime

5 annotation is for the primary key.

	org.springframework.boot
	spring-boot-starter-data-jpa



	org.springframework.boot
	spring-boot-starter-web



	org.apache.poi
	poi-ooxml
	4.1.2



	mysql
	mysql-connector-java
	runtime

6 annotation is used to define the column in database that maps annotated field.

Tạo kho lưu trữ dữ liệu để làm việc với cơ sở dữ liệu

Thực hiện Lớp trợ giúp đọc/Viết Excel
In repository package, create

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i8 interface that extends 
package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i9.

repository/TutorialRepository.java

package com.bezkoder.spring.files.excel.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.bezkoder.spring.files.excel.model.Tutorial;

public interface TutorialRepository extends JpaRepository {
}

Tạo dịch vụ tệp Excel

Xác định thông báo phản hồitutorials table) could be large, so you may want to get only several at once by modifying this Repository to work with Pagination, the instruction can be found at:
Spring Boot Pagination & Filter example | Spring JPA, Pageable

Các truy vấn có nguồn gốc nhiều hơn tại: Ví dụ truy vấn kho lưu trữ JPA trong khởi động mùa xuân
JPA Repository query example in Spring Boot

Truy vấn tùy chỉnh với

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
6 chú thích: Spring JPA @Query Ví dụ: Truy vấn tùy chỉnh trong khởi động mùa xuân
Spring JPA @Query example: Custom query in Spring Boot

Bạn cũng tìm cách viết bài kiểm tra đơn vị cho kho lưu trữ JPA này tại: Thử nghiệm đơn vị khởi động Spring cho JPA Repositiory với @DataJPatest
Spring Boot Unit Test for JPA Repositiory with @DataJpaTest

Thực hiện Lớp trợ giúp đọc/Viết Excel

Chúng tôi sẽ sử dụng các lớp Apache POI như:

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
7,
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
8,
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
9,
package com.bezkoder.spring.files.excel.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tutorials")
public class Tutorial {

  @Id
  @Column(name = "id")
  private long id;

  @Column(name = "title")
  private String title;

  @Column(name = "description")
  private String description;

  @Column(name = "published")
  private boolean published;

  public Tutorial() {

  }

  public Tutorial(String title, String description, boolean published) {
    this.title = title;
    this.description = description;
    this.published = published;
  }

  public long getId() {
    return id;
  }

  public void setId(long id) {
    this.id = id;
  }

  public String getTitle() {
    return title;
  }

  public void setTitle(String title) {
    this.title = title;
  }

  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

  public boolean isPublished() {
    return published;
  }

  public void setPublished(boolean isPublished) {
    this.published = isPublished;
  }

  @Override
  public String toString() {
    return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
  }
}
0. Hãy để tôi tóm tắt các bước để đọc từ tệp Excel:
Let me summarize the steps for reading from Excel file:

  • Tạo
    spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
    spring.datasource.username= root
    spring.datasource.password= 123456
    
    spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
    
    # Hibernate ddl auto (create, create-drop, validate, update)
    spring.jpa.hibernate.ddl-auto= update
    
    7 từ
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    2
  • Tạo
    spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
    spring.datasource.username= root
    spring.datasource.password= 123456
    
    spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
    
    # Hibernate ddl auto (create, create-drop, validate, update)
    spring.jpa.hibernate.ddl-auto= update
    
    8 bằng phương pháp
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    4
  • lặp lại trên
    spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
    spring.datasource.username= root
    spring.datasource.password= 123456
    
    spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
    
    # Hibernate ddl auto (create, create-drop, validate, update)
    spring.jpa.hibernate.ddl-auto= update
    
    9S bởi
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    6 với
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    7 và
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    8
  • Từ mỗi
    spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
    spring.datasource.username= root
    spring.datasource.password= 123456
    
    spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
    
    # Hibernate ddl auto (create, create-drop, validate, update)
    spring.jpa.hibernate.ddl-auto= update
    
    9, lặp đi lặp lại trên
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    0s
  • Với mỗi
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    0, sử dụng
    package com.bezkoder.spring.files.excel.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public interface TutorialRepository extends JpaRepository {
    }
    
    2, ________ 63 Phương pháp để đọc và phân tích nội dung
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();

Trong gói Helper, chúng tôi tạo lớp

package com.bezkoder.spring.files.excel.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.bezkoder.spring.files.excel.model.Tutorial;

public interface TutorialRepository extends JpaRepository {
}
4 với 2 phương thức:helper package, we create
package com.bezkoder.spring.files.excel.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.bezkoder.spring.files.excel.model.Tutorial;

public interface TutorialRepository extends JpaRepository {
}
4 class with 2 methods:

  • package com.bezkoder.spring.files.excel.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public interface TutorialRepository extends JpaRepository {
    }
    
    5: Kiểm tra xem tệp có định dạng excel hay không
  • package com.bezkoder.spring.files.excel.repository;
    
    import org.springframework.data.jpa.repository.JpaRepository;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public interface TutorialRepository extends JpaRepository {
    }
    
    6: Đọc
    package com.bezkoder.spring.files.excel.model;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "tutorials")
    public class Tutorial {
    
      @Id
      @Column(name = "id")
      private long id;
    
      @Column(name = "title")
      private String title;
    
      @Column(name = "description")
      private String description;
    
      @Column(name = "published")
      private boolean published;
    
      public Tutorial() {
    
      }
    
      public Tutorial(String title, String description, boolean published) {
        this.title = title;
        this.description = description;
        this.published = published;
      }
    
      public long getId() {
        return id;
      }
    
      public void setId(long id) {
        this.id = id;
      }
    
      public String getTitle() {
        return title;
      }
    
      public void setTitle(String title) {
        this.title = title;
      }
    
      public String getDescription() {
        return description;
      }
    
      public void setDescription(String description) {
        this.description = description;
      }
    
      public boolean isPublished() {
        return published;
      }
    
      public void setPublished(boolean isPublished) {
        this.published = isPublished;
      }
    
      @Override
      public String toString() {
        return "Tutorial [id=" + id + ", title=" + title + ", desc=" + description + ", published=" + published + "]";
      }
    }
    
    2 của một tệp, trả lại danh sách các hướng dẫn

Dưới đây là mã đầy đủ của người trợ giúp/excelhelper.java:

package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}

Don Tiết quên thay đổi tên trang tính thành các hướng dẫn (hoặc bất kỳ tên nào bạn muốn). Nó khác vì chúng tôi tạo đối tượng

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
8 từ tên đó.Tutorials (or any name you want). It’s because we create
spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
8 object from that name.

static String SHEET = "Tutorials";
...
Sheet sheet = workbook.getSheet(SHEET);

Tạo dịch vụ tệp Excel

Lớp

"Content-disposition" : "attachment; filename=[yourFileName]" 
"Content-Type" : "application/vnd.ms-excel"
0 sẽ được chú thích với chú thích
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
0, nó sử dụng
package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i6 và 
package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i8 cho 2 chức năng:

  • Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet sheet = workbook.getSheet(SHEET);
    Iterator rows = sheet.iterator();
    
    while (rows.hasNext()) {
      Row currentRow = rows.next();
    
      Iterator cellsInRow = currentRow.iterator();
    
      while (cellsInRow.hasNext()) {
         Cell currentCell = cellsInRow.next();
    
         // each cell case
         id = (long) currentCell.getNumericCellValue();
         title = currentCell.getStringCellValue();
         published = currentCell.getBooleanCellValue();
      }
         
    workbook.close();
    
    3: Lưu trữ dữ liệu Excel vào cơ sở dữ liệu
  • ________ 74 (): Đọc dữ liệu từ cơ sở dữ liệu và trả về
    Workbook workbook = new XSSFWorkbook(inputStream);
    Sheet sheet = workbook.getSheet(SHEET);
    Iterator rows = sheet.iterator();
    
    while (rows.hasNext()) {
      Row currentRow = rows.next();
    
      Iterator cellsInRow = currentRow.iterator();
    
      while (cellsInRow.hasNext()) {
         Cell currentCell = cellsInRow.next();
    
         // each cell case
         id = (long) currentCell.getNumericCellValue();
         title = currentCell.getStringCellValue();
         published = currentCell.getBooleanCellValue();
      }
         
    workbook.close();
    
    5

service/ExcelService.java/ExcelService.java

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i0

Xác định thông báo phản hồi

Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
6 dành cho tin nhắn cho khách hàng mà chúng tôi sẽ sử dụng trong bộ điều khiển REST và bộ xử lý ngoại lệ.

Tin nhắn/Trả lời DEMEMESSAGE.java/ResponseMessage.java

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i1

Tạo bộ điều khiển để tải lên các tệp excel

Trong gói bộ điều khiển, chúng tôi tạo lớp

"Content-disposition" : "attachment; filename=[yourFileName]" 
"Content-Type" : "application/vnd.ms-excel"
3 cho API REST. -
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
8 là để cấu hình nguồn gốc được phép. - Chú thích
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
9 chỉ ra rằng đây là bộ điều khiển. - Chú thích
package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
0 và
package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
1 dành cho ánh xạ HTTP GET & POST yêu cầu lên các phương thức xử lý cụ thể:controller package, we create
"Content-disposition" : "attachment; filename=[yourFileName]" 
"Content-Type" : "application/vnd.ms-excel"
3 class for Rest Apis.
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
8 is for configuring allowed origins.
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet sheet = workbook.getSheet(SHEET);
Iterator rows = sheet.iterator();

while (rows.hasNext()) {
  Row currentRow = rows.next();

  Iterator cellsInRow = currentRow.iterator();

  while (cellsInRow.hasNext()) {
     Cell currentCell = cellsInRow.next();

     // each cell case
     id = (long) currentCell.getNumericCellValue();
     title = currentCell.getStringCellValue();
     published = currentCell.getBooleanCellValue();
  }
     
workbook.close();
9 annotation indicates that this is a controller.
package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
0 and
package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
1 annotation is for mapping HTTP GET & POST requests onto specific handler methods:

  • Đăng /Tải lên:
    package com.bezkoder.spring.files.excel.helper;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public class ExcelHelper {
      public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      static String[] HEADERs = { "Id", "Title", "Description", "Published" };
      static String SHEET = "Tutorials";
    
      public static boolean hasExcelFormat(MultipartFile file) {
    
        if (!TYPE.equals(file.getContentType())) {
          return false;
        }
    
        return true;
      }
    
      public static List excelToTutorials(InputStream is) {
        try {
          Workbook workbook = new XSSFWorkbook(is);
    
          Sheet sheet = workbook.getSheet(SHEET);
          Iterator rows = sheet.iterator();
    
          List tutorials = new ArrayList();
    
          int rowNumber = 0;
          while (rows.hasNext()) {
            Row currentRow = rows.next();
    
            // skip header
            if (rowNumber == 0) {
              rowNumber++;
              continue;
            }
    
            Iterator cellsInRow = currentRow.iterator();
    
            Tutorial tutorial = new Tutorial();
    
            int cellIdx = 0;
            while (cellsInRow.hasNext()) {
              Cell currentCell = cellsInRow.next();
    
              switch (cellIdx) {
              case 0:
                tutorial.setId((long) currentCell.getNumericCellValue());
                break;
    
              case 1:
                tutorial.setTitle(currentCell.getStringCellValue());
                break;
    
              case 2:
                tutorial.setDescription(currentCell.getStringCellValue());
                break;
    
              case 3:
                tutorial.setPublished(currentCell.getBooleanCellValue());
                break;
    
              default:
                break;
              }
    
              cellIdx++;
            }
    
            tutorials.add(tutorial);
          }
    
          workbook.close();
    
          return tutorials;
        } catch (IOException e) {
          throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
        }
      }
    }
    
    2
  • Nhận /Hướng dẫn:
    package com.bezkoder.spring.files.excel.helper;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public class ExcelHelper {
      public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      static String[] HEADERs = { "Id", "Title", "Description", "Published" };
      static String SHEET = "Tutorials";
    
      public static boolean hasExcelFormat(MultipartFile file) {
    
        if (!TYPE.equals(file.getContentType())) {
          return false;
        }
    
        return true;
      }
    
      public static List excelToTutorials(InputStream is) {
        try {
          Workbook workbook = new XSSFWorkbook(is);
    
          Sheet sheet = workbook.getSheet(SHEET);
          Iterator rows = sheet.iterator();
    
          List tutorials = new ArrayList();
    
          int rowNumber = 0;
          while (rows.hasNext()) {
            Row currentRow = rows.next();
    
            // skip header
            if (rowNumber == 0) {
              rowNumber++;
              continue;
            }
    
            Iterator cellsInRow = currentRow.iterator();
    
            Tutorial tutorial = new Tutorial();
    
            int cellIdx = 0;
            while (cellsInRow.hasNext()) {
              Cell currentCell = cellsInRow.next();
    
              switch (cellIdx) {
              case 0:
                tutorial.setId((long) currentCell.getNumericCellValue());
                break;
    
              case 1:
                tutorial.setTitle(currentCell.getStringCellValue());
                break;
    
              case 2:
                tutorial.setDescription(currentCell.getStringCellValue());
                break;
    
              case 3:
                tutorial.setPublished(currentCell.getBooleanCellValue());
                break;
    
              default:
                break;
              }
    
              cellIdx++;
            }
    
            tutorials.add(tutorial);
          }
    
          workbook.close();
    
          return tutorials;
        } catch (IOException e) {
          throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
        }
      }
    }
    
    3

- Chúng tôi sử dụng

package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
4 để đưa thực hiện
"Content-disposition" : "attachment; filename=[yourFileName]" 
"Content-Type" : "application/vnd.ms-excel"
0 Bean vào biến cục bộ.

controller/ExcelController.java/ExcelController.java

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i2

Định cấu hình Tệp nhiều phần cho Servlet

Hãy để xác định kích thước tệp tối đa có thể được tải lên trong application.properies như sau:

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i3
  • package com.bezkoder.spring.files.excel.helper;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public class ExcelHelper {
      public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      static String[] HEADERs = { "Id", "Title", "Description", "Published" };
      static String SHEET = "Tutorials";
    
      public static boolean hasExcelFormat(MultipartFile file) {
    
        if (!TYPE.equals(file.getContentType())) {
          return false;
        }
    
        return true;
      }
    
      public static List excelToTutorials(InputStream is) {
        try {
          Workbook workbook = new XSSFWorkbook(is);
    
          Sheet sheet = workbook.getSheet(SHEET);
          Iterator rows = sheet.iterator();
    
          List tutorials = new ArrayList();
    
          int rowNumber = 0;
          while (rows.hasNext()) {
            Row currentRow = rows.next();
    
            // skip header
            if (rowNumber == 0) {
              rowNumber++;
              continue;
            }
    
            Iterator cellsInRow = currentRow.iterator();
    
            Tutorial tutorial = new Tutorial();
    
            int cellIdx = 0;
            while (cellsInRow.hasNext()) {
              Cell currentCell = cellsInRow.next();
    
              switch (cellIdx) {
              case 0:
                tutorial.setId((long) currentCell.getNumericCellValue());
                break;
    
              case 1:
                tutorial.setTitle(currentCell.getStringCellValue());
                break;
    
              case 2:
                tutorial.setDescription(currentCell.getStringCellValue());
                break;
    
              case 3:
                tutorial.setPublished(currentCell.getBooleanCellValue());
                break;
    
              default:
                break;
              }
    
              cellIdx++;
            }
    
            tutorials.add(tutorial);
          }
    
          workbook.close();
    
          return tutorials;
        } catch (IOException e) {
          throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
        }
      }
    }
    
    6: Kích thước tệp tối đa cho mỗi yêu cầu.
  • package com.bezkoder.spring.files.excel.helper;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.springframework.web.multipart.MultipartFile;
    
    import com.bezkoder.spring.files.excel.model.Tutorial;
    
    public class ExcelHelper {
      public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      static String[] HEADERs = { "Id", "Title", "Description", "Published" };
      static String SHEET = "Tutorials";
    
      public static boolean hasExcelFormat(MultipartFile file) {
    
        if (!TYPE.equals(file.getContentType())) {
          return false;
        }
    
        return true;
      }
    
      public static List excelToTutorials(InputStream is) {
        try {
          Workbook workbook = new XSSFWorkbook(is);
    
          Sheet sheet = workbook.getSheet(SHEET);
          Iterator rows = sheet.iterator();
    
          List tutorials = new ArrayList();
    
          int rowNumber = 0;
          while (rows.hasNext()) {
            Row currentRow = rows.next();
    
            // skip header
            if (rowNumber == 0) {
              rowNumber++;
              continue;
            }
    
            Iterator cellsInRow = currentRow.iterator();
    
            Tutorial tutorial = new Tutorial();
    
            int cellIdx = 0;
            while (cellsInRow.hasNext()) {
              Cell currentCell = cellsInRow.next();
    
              switch (cellIdx) {
              case 0:
                tutorial.setId((long) currentCell.getNumericCellValue());
                break;
    
              case 1:
                tutorial.setTitle(currentCell.getStringCellValue());
                break;
    
              case 2:
                tutorial.setDescription(currentCell.getStringCellValue());
                break;
    
              case 3:
                tutorial.setPublished(currentCell.getBooleanCellValue());
                break;
    
              default:
                break;
              }
    
              cellIdx++;
            }
    
            tutorials.add(tutorial);
          }
    
          workbook.close();
    
          return tutorials;
        } catch (IOException e) {
          throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
        }
      }
    }
    
    7: Kích thước yêu cầu tối đa cho nhiều dữ liệu/hình thức.

Xử lý ngoại lệ tải lên tệp

Đây là nơi chúng tôi xử lý trường hợp ở chỗ yêu cầu vượt quá kích thước tải lên tối đa. Hệ thống sẽ ném

package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
8 và chúng tôi sẽ sử dụng
package com.bezkoder.spring.files.excel.helper;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import com.bezkoder.spring.files.excel.model.Tutorial;

public class ExcelHelper {
  public static String TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
  static String[] HEADERs = { "Id", "Title", "Description", "Published" };
  static String SHEET = "Tutorials";

  public static boolean hasExcelFormat(MultipartFile file) {

    if (!TYPE.equals(file.getContentType())) {
      return false;
    }

    return true;
  }

  public static List excelToTutorials(InputStream is) {
    try {
      Workbook workbook = new XSSFWorkbook(is);

      Sheet sheet = workbook.getSheet(SHEET);
      Iterator rows = sheet.iterator();

      List tutorials = new ArrayList();

      int rowNumber = 0;
      while (rows.hasNext()) {
        Row currentRow = rows.next();

        // skip header
        if (rowNumber == 0) {
          rowNumber++;
          continue;
        }

        Iterator cellsInRow = currentRow.iterator();

        Tutorial tutorial = new Tutorial();

        int cellIdx = 0;
        while (cellsInRow.hasNext()) {
          Cell currentCell = cellsInRow.next();

          switch (cellIdx) {
          case 0:
            tutorial.setId((long) currentCell.getNumericCellValue());
            break;

          case 1:
            tutorial.setTitle(currentCell.getStringCellValue());
            break;

          case 2:
            tutorial.setDescription(currentCell.getStringCellValue());
            break;

          case 3:
            tutorial.setPublished(currentCell.getBooleanCellValue());
            break;

          default:
            break;
          }

          cellIdx++;
        }

        tutorials.add(tutorial);
      }

      workbook.close();

      return tutorials;
    } catch (IOException e) {
      throw new RuntimeException("fail to parse Excel file: " + e.getMessage());
    }
  }
}
9 với
static String SHEET = "Tutorials";
...
Sheet sheet = workbook.getSheet(SHEET);
0Annotation để xử lý các trường hợp ngoại lệ.

exception/FileUploadExceptionAdvice.java

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i4

Chạy & Kiểm tra

Chạy ứng dụng khởi động mùa xuân với lệnh:

static String SHEET = "Tutorials";
...
Sheet sheet = workbook.getSheet(SHEET);
1.

Hãy để sử dụng Postman để thực hiện một số yêu cầu.Postman to make some requests.

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Nếu bạn tải lên một tệp có kích thước lớn hơn kích thước tệp tối đa (2MB):

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Sự kết luận

Hôm nay, chúng tôi đã xây dựng API CRUD REST bằng cách sử dụng Spring Boot để tải và nhập dữ liệu từ tệp Excel sang bảng cơ sở dữ liệu MySQL.

Chúng tôi cũng thấy cách sử dụng Apache POI để đọc dữ liệu từ tờ Excel,

package com.example.SpringBootExcelReader;

import java.io.IOException;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
public class ExcelController {

	@PostMapping("excel")
	public String excelReader(@RequestParam("file") MultipartFile excel) {
		
		try {
			XSSFWorkbook workbook = new XSSFWorkbook(excel.getInputStream());
			XSSFSheet sheet = workbook.getSheetAt(0);
			
			for(int i=0; i9 để truy xuất các mục trong bảng cơ sở dữ liệu mà không cần mã Boilerplate.

Các truy vấn có nguồn gốc nhiều hơn tại: Ví dụ truy vấn kho lưu trữ JPA trong khởi động mùa xuân
JPA Repository query example in Spring Boot

Truy vấn tùy chỉnh với

spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
spring.datasource.username= root
spring.datasource.password= 123456

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect

# Hibernate ddl auto (create, create-drop, validate, update)
spring.jpa.hibernate.ddl-auto= update
6 chú thích: Spring JPA @Query Ví dụ: Truy vấn tùy chỉnh trong khởi động mùa xuân
Spring JPA @Query example: Custom query in Spring Boot

Nếu bạn muốn thêm phân trang vào dự án mùa xuân này, bạn có thể tìm thấy hướng dẫn tại: Ví dụ về Pagination & Filter Spring Boot | JPA mùa xuân, có thể ngà
Spring Boot Pagination & Filter example | Spring JPA, Pageable

Để tải xuống tệp Excel: Spring Boot: Tải xuống tệp Excel từ Bảng cơ sở dữ liệu MySQL
Spring Boot: Download Excel file from MySQL database table

Tải lên tệp CSV thay thế: Spring Boot: Tải dữ liệu tệp CSV vào cơ sở dữ liệu MySQL
Spring Boot: Upload CSV file Data into MySQL Database

Hoặc tải lên các tệp lên cơ sở dữ liệu dưới dạng blob: spring khởi động tải lên/tải xuống tệp lên/từ cơ sở dữ liệu ví dụ
Spring Boot Upload/Download File to/from Database example

Hướng dẫn read excel file java spring boot - đọc file excel java khởi động mùa xuân

Học hỏi! Hẹn gặp lại.

Đọc thêm

  • Tài liệu tham khảo JPA dữ liệu mùa xuân
  • https://github.com/apache/poi

Triển khai: - Triển khai ứng dụng khởi động mùa xuân trên AWS - Beanstalk đàn hồi - Docker Compose: Spring Boot và MySQL Ví dụ
– Deploy Spring Boot App on AWS – Elastic Beanstalk
– Docker Compose: Spring Boot and MySQL example

Mã nguồn

Bạn có thể tìm thấy mã nguồn đầy đủ cho hướng dẫn này trên GitHub.

Làm cách nào để đọc tệp XLSX trong Spring Boot?

Hãy để tôi tóm tắt các bước để đọc từ tệp Excel:..
Tạo sổ làm việc từ InputStream ..
Tạo trang tính bằng cách sử dụng sổ làm việc. phương thức getSheet () ..
lặp qua hàng s bởi tererator với tấm. iterator () và iterator. ....
Từ mỗi hàng, lặp lại trên ô ..
Với mỗi ô, hãy sử dụng getNumericCellValue (), getTringCellValue ().

Làm thế nào đọc Excel và Excel trong Java?

Các bước để ghi dữ liệu vào tệp XLS trong Java..
Bao gồm poi-3.12.jar trong đường dẫn lớp của chương trình Java của bạn ..
Tạo một đối tượng của HSSFWorkbook ..
Tạo một tờ trên sổ làm việc đó bằng cách gọi phương thức Createsheet () ..
Tạo một hàng trên bảng đó bằng cách gọi phương thức createrow () ..
Tạo một ô bằng cách gọi phương thức Createcell () ..

Làm cách nào để đọc một tệp excel hiện có trong java?

Ví dụ về việc đọc tệp tệp excel (.xls)..
nhập java.io.file ;.
nhập java.io.fileinputstream ;.
nhập java.io.ioException ;.
Nhập org.apache.poi.hssf.usermodel.hssfsheet ;.
Nhập org.apache.poi.hssf.usermodel.hssfworkbook ;.
Nhập org.apache.poi.sss.usermodel.cell ;.
Nhập org.apache.poi.sss.usermodel.formulaEvalUator ;.

Làm cách nào để đọc dữ liệu từ bảng tính excel?

Để đọc dữ liệu từ các ô Excel, hãy sử dụng đối tượng thời gian chạy Excel.Trong một số trường hợp nâng cao, ví dụ, khi bạn làm việc với các phạm vi ô trong các tệp Excel, bạn có thể sử dụng Excel.Ứng dụng đối tượng com.use the Excel runtime object. In some advanced cases, for instance, when you work with ranges of cells in Excel files, you can use the Excel. Application COM object.