Nhập excel trong Spring boot

Apache POI là một thư viện mã nguồn mở được cung cấp bởi apache được sử dụng để xử lý các tệp văn phòng như word, excel, powerpoint…

1. 1 Xử lý file Excel với Apache POI

Apache POI xử lý các thành phần trong excel theo hướng đối tượng lập trình đúng – mỗi thành phần trong Excel đều được coi là 1 đối tượng

Các lớp cơ bản được sử dụng để đọc tệp Excel

  • HSSF. các lớp có tên bắt đầu là HSSF được sử dụng để sử lý các tệp Microsoft Excel 2003 (. xls)
  • XSSF. các lớp có tên bắt đầu là XSSF được sử dụng để quản lý các tệp Microsoft Excel 2007 trở về sau (. xlsx)
  • XSSFWorkbook và HSSFWorkbook là các lớp xử lý Excel Workbook
  • HSSFSheet và XSSFSheet là các lớp xử lý với Excel Worksheet
  • Hàng ngang. định nghĩa một dòng trong excel
  • Tế bào. định nghĩa một ô trong excel

(Xem thêm. phân biệt workbook với worksheet)

2. Tải xuống thư viện Apache POI

Ở đây mình sử dụng maven để lấy thư viện của Apache POI

  • Chọn các tập tin Microsoft Excel 2003

    org.apache.poi
    poi
    3.17

  • Cho các tập tin Microsoft Excel 2007 trở về sau

    org.apache.poi
    poi-ooxml
    3.17

 

3. Read write file Excel bằng Apache POI

3. 1 Ghi file Excel

Ví dụ đoạn code dưới đây tạo 1 file excel có tên là “Demo-ApachePOI-Excel. xlsx”

Tạo 1 Worksheet có tên là “Customer_Info”

dòng đầu tiên hiển thị “Danh sách khách hàng”

Các dòng tiếp theo hiển thị các thông tin của khách hàng (id, name, email), mỗi thông tin ở 1 cột

package stackjava.com.apachepoiexcel.demo;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class WriteFileExcel {

  public static void main(String[] args) {
    System.out.println("Create file excel");
    XSSFWorkbook workbook = new XSSFWorkbook();
    XSSFSheet sheet = workbook.createSheet("Customer_Info");
    int rowNum = 0;
    Row firstRow = sheet.createRow(rowNum++);
    Cell firstCell = firstRow.createCell(0);
    firstCell.setCellValue("List of Customer");

    List listOfCustomer = new ArrayList();
    listOfCustomer.add(new Customer(1, "Sylvester Stallone", "[email protected]"));
    listOfCustomer.add(new Customer(2, "Tom Cruise", "[email protected]"));
    listOfCustomer.add(new Customer(3, "Vin Diesel", "[email protected]"));

    for (Customer customer : listOfCustomer) {
      Row row = sheet.createRow(rowNum++);
      Cell cell1 = row.createCell(0);
      cell1.setCellValue(customer.getId());

      Cell cell2 = row.createCell(1);
      cell2.setCellValue(customer.getName());

      Cell cell3 = row.createCell(2);
      cell3.setCellValue(customer.getEmail());
    }

    try {
      FileOutputStream outputStream = new FileOutputStream("Demo-ApachePOI-Excel.xlsx");
      workbook.write(outputStream);
      workbook.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    System.out.println("Done");
  }
}
package stackjava.com.apachepoiexcel.demo;

public class Customer {
  private int id;
  private String name;
  private String email;

  // setter - getter

}

Kết quả

Nhập excel trong Spring boot

3. 2 Đọc file Excel

Bây giờ mình sẽ thực hiện đọc lại file Excel vừa tạo ở trên

package stackjava.com.apachepoiexcel.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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.DataFormatter;
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;

public class ReadFileExcel {

  public static void main(String[] args) {

    try {
      FileInputStream excelFile = new FileInputStream(new File("Demo-ApachePOI-Excel.xlsx"));
      Workbook workbook = new XSSFWorkbook(excelFile);
      Sheet datatypeSheet = workbook.getSheetAt(0);
      DataFormatter fmt = new DataFormatter();

      Iterator iterator = datatypeSheet.iterator();
      Row firstRow = iterator.next();
      Cell firstCell = firstRow.getCell(0);
      System.out.println(firstCell.getStringCellValue());
      List listOfCustomer = new ArrayList();
      while (iterator.hasNext()) {
        Row currentRow = iterator.next();
        Customer customer = new Customer();
        customer.setId(Integer.parseInt(fmt.formatCellValue(currentRow.getCell(0))));
        customer.setName(currentRow.getCell(1).getStringCellValue());
        customer.setEmail(currentRow.getCell(2).getStringCellValue());
        listOfCustomer.add(customer);
      }

      for (Customer customer : listOfCustomer) {
        System.out.println(customer);
      }
      workbook.close();
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

*Lưu ý. id của khách hàng là số nguyên nên khi ghi vào file excel nó sẽ là kiểu số, do đó khi đọc ra thì nó sẽ đọc là số và chuyển thành double, ví dụ 1 sẽ là 1. 0. Do đó ta sử dụng DataFormatter để định dạng nó về kiểu chuỗi và phân tích lại thành số nguyên.