Làm thế nào để bạn đọc dữ liệu excel và lưu trữ nó trong cơ sở dữ liệu bằng java?

Nhiều khách hàng cung cấp dữ liệu của họ ở dạng bảng excel và yêu cầu nhà phát triển lưu dữ liệu đó vào cơ sở dữ liệu của bạn. Nếu bạn đã từng thực hiện ‘Cách Upload dữ liệu excel vào Database bằng Spring Boot’ thì tốt. Nếu không, không phải lo lắng. , chúng ta sẽ tìm hiểu tương tự trong bài viết này. Cuối cùng, bạn sẽ thấy nó rất dễ dàng và nhanh chóng để hoàn thành. Trên thực tế, khi bạn xem qua toàn bộ bài viết, bạn sẽ nhận thấy rằng bạn chỉ cần cung cấp vị trí tệp excel của mình trong ứng dụng. tệp thuộc tínhBạn sẽ nhận được dữ liệu được tải lên cơ sở dữ liệu bằng cách chỉ thực hiện các thay đổi nhỏ trong các lớp thực thể của riêng bạn

Chúng tôi sẽ không thúc đẩy bất kỳ mã hóa cứng nào trong quá trình triển khai của chúng tôi. Ngay cả khi bạn đang làm việc lần đầu trong ứng dụng web Spring Boot, bạn sẽ dễ dàng triển khai chức năng này bằng cách thực hiện theo các bước được đề cập tại đây. Hơn nữa, để thoát khỏi mã hóa cứng, chúng tôi sẽ lấy một số giá trị từ tệp thuộc tính để chúng tôi không sửa đổi tệp java trong trường hợp chúng tôi có bất kỳ yêu cầu thay đổi nào trong tương lai. Ngoài ra, chúng tôi sẽ sử dụng Apache POI phổ biến nhất. API Java dành cho Tài liệu của Microsoft trong quá trình triển khai của chúng tôi. Bây giờ chúng ta đi vào chủ đề “Cách Upload dữ liệu Excel vào Database bằng Spring Boot”

Mục lục (Nhấp vào liên kết bên dưới để điều hướng)

  • 1 Bạn sẽ nhận được tất cả chức năng/tính năng nào từ bài viết này?
  • 2 Bạn sẽ học được gì sau khi triển khai ứng dụng này?
  • 3 Bạn có thể tự thực hiện tất cả những triển khai nào sau khi xem qua ví dụ này?
  • 4 Phần mềm được sử dụng trong dự án này
    • 4. 1 Phụ thuộc bên ngoài
  • 5 Điều kiện tiên quyết
  • 6 Các bước mã hóa
    • 6. 1 — Tạo dự án trong STS
      • 6. 1. 1 Nơi đặt tệp JSP?
    • 6. 2 — Viết các lớp Java, JSP & Cập nhật ứng dụng. thuộc tính
      • 6. 2. 1 Trình điều khiển hóa đơn. java
      • 6. 2. 2 Hóa đơn. java
      • 6. 2. 3 Kho lưu trữ hóa đơn. java
      • 6. 2. 4 Dịch vụ IExcelData. java
      • 6. 2. 5 Dịch vụ IFileUploader. java
      • 6. 2. 6 ExcelDataServiceImpl. java
      • 6. 2. 7 FileUploaderServiceImpl. java
      • 6. 2. 8 ứng dụng. thuộc tính
      • 6. 2. 9 trang tải lên. jsp
      • 6. 2. 10 thành công. jsp
  • 7 Ứng dụng đang chạy
  • 8 Kết quả kiểm tra
  • 9 Làm cách nào để thực hiện triển khai của riêng chúng tôi từ Ví dụ này với những thay đổi tối thiểu?
  • 10 Chúng tôi có thể sử dụng triển khai này trong một dự án thực không?
  • 11 Chúng tôi cần thực hiện những thay đổi nào nếu muốn sử dụng chức năng này trong dự án thực của mình?
  • 12 Kết luận

Bạn sẽ nhận được tất cả chức năng/tính năng nào từ bài viết này?

1) Cách lưu dữ liệu vào cơ sở dữ liệu nếu dữ liệu đầu vào ở dạng excel sheet.
2) Cách tải lên bất kỳ tệp nào (ngoài excel) bằng trình duyệt web.
3) Hai chức năng trên không phụ thuộc lẫn nhau. Chúng tôi có thể thực hiện từng chức năng riêng biệt.
3) Apache POI Phiên bản mới nhất (hiện tại là 4. 1. 2) đã được sử dụng để thực hiện dự án.
4) Ngoài ra, mã được thử nghiệm thành công trên các phiên bản JDK8, JDK9 và thậm chí cả JDK14.
5) Làm cách nào để đọc dữ liệu từ trang tính excel và chèn vào bảng cơ sở dữ liệu trong khởi động mùa xuân?

Bạn sẽ học được gì sau khi thực hiện ứng dụng này?

1) Làm cách nào để tạo ứng dụng web Spring Boot kết hợp thiết kế dự án cấp ngành?

2) Cách thiết kế ứng dụng web Java, bao gồm tất cả các lớp sử dụng Trình điều khiển, Dịch vụ, Kho lưu trữ, Giao diện người dùng, v.v. như trong thiết kế dự án thời gian thực?

3) Quan trọng không kém, Vị trí và cách sử dụng Chú thích như @Value, @Autowired, @Controller, @Service, @Repository, @Entity, @Id, @GeneratedValue, @GetMapping, @PostMapping, v.v.

4) Ngoài ra, Làm việc với giao diện kho lưu trữ Spring Boot Data JPA

5) Triển khai Apache POI phổ biến nhất (API Java cho Tài liệu Microsoft)

6) Sau đó, Cách làm việc với ứng dụng. tệp thuộc tính?

7) Làm cách nào để tải dữ liệu theo lô lên cơ sở dữ liệu bằng Spring Boot?

8) Ngoài ra, Làm cách nào để viết mã mô-đun và mã có thể tái sử dụng?

9) Làm cách nào để triển khai mã động với các thay đổi tối thiểu, lưu ý đến các yêu cầu thay đổi trong tương lai?

10) Làm cách nào để viết mã mà không cần mã hóa cứng các giá trị bằng Spring Boot?

11) Cuối cùng nhưng không kém phần quan trọng, bạn sẽ học “Cách tải dữ liệu Excel vào cơ sở dữ liệu bằng Spring Boot”

12) Đặc biệt, Cách đọc dữ liệu từ sheet excel và chèn vào bảng cơ sở dữ liệu trong spring boot

Bạn có thể tự thực hiện tất cả những triển khai nào sau khi xem qua ví dụ này?

1) Làm cách nào để đọc dữ liệu từ trang tính excel và chèn vào bảng cơ sở dữ liệu trong spring mvc?

2) Làm cách nào để tải tệp excel lên cơ sở dữ liệu bằng khởi động mùa xuân?

3) ví dụ tải lên tệp excel khởi động mùa xuân

4) Làm cách nào để đọc dữ liệu từ trang tính excel và chèn vào bảng cơ sở dữ liệu trong khởi động mùa xuân?

5) Làm cách nào để nhập dữ liệu từ excel sang mysql bằng spring boot?

6) Làm cách nào để tải tệp excel lên cơ sở dữ liệu bằng java?

7) Làm thế nào để đọc tệp excel trong ví dụ khởi động mùa xuân?

8) Làm cách nào để đọc dữ liệu từ excel và lưu trữ trong datatable trong java?

9) Làm cách nào để tải lên và đọc tệp excel trong khởi động mùa xuân?

10) Cách viết mã java để đọc file excel và chèn vào cơ sở dữ liệu?

11) Làm cách nào để nhập dữ liệu excel vào cơ sở dữ liệu bằng java?

12) Làm cách nào để tải tệp Excel lên cơ sở dữ liệu bằng Apache POI và Spring Framework?

Phần mềm được sử dụng trong dự án này

♦ STS (Bộ công cụ mùa xuân). Phiên bản-> 4. 7. 1. PHÁT HÀNH
⇒ Người mới bắt đầu phụ thuộc. Spring Web, Spring Data JPA, Trình điều khiển MySql
♦ Cơ sở dữ liệu MySQL. Phiên bản ->8. 0. 19 Máy chủ cộng đồng MySQL
♦ Các phiên bản JDK8 trở lên (Đã được thử nghiệm kỹ lưỡng trên JDK8, JDK9 và JDK14)

Phụ thuộc bên ngoài

Chúng tôi sẽ thêm phụ thuộc apache 'poi-ooxml' sau vào pom. xml vì nó là một jar bên ngoài để có được các tính năng của Microsoft Excel


    org.apache.poi
    poi-ooxml
    4.1.2

điều kiện tiên quyết

Bạn nên chuẩn bị sẵn một cơ sở dữ liệu để lưu trữ dữ liệu từ file excel. Nếu không thì tạo cơ sở dữ liệu MySQL để lưu dữ liệu. Tuy nhiên, nếu bạn chỉ muốn kiểm tra chức năng, bạn có thể sử dụng các cấu hình của chúng tôi làm tên cơ sở dữ liệu 'exceldata' và tên bảng 'hóa đơn' tương ứng

Các bước mã hóa

— Tạo dự án trong STS

Nếu bạn là người mới trong Spring Boot, hãy truy cập Liên kết nội bộ để tạo một dự án mẫu trong khởi động mùa xuân. Trong khi tạo dự án trong STS, hãy thêm 3 phần khởi động 'Trình điều khiển MySql', 'JPA dữ liệu mùa xuân' và 'Web mùa xuân'. Bạn cũng có thể thêm tùy chọn 'Spring Boot DevTools'

Đặt các tệp tin JSP ở đâu?

Để chứa các tệp JSP,

1) tạo thư mục 'ứng dụng web' trong src/main/
2) trong 'ứng dụng web' tạo thư mục 'WEB-INF'
3) .
4) Bây giờ hệ thống phân cấp cấu trúc Thư mục của bạn sẽ giống như “src/main/webapps/WEB-INF/pages”.

— Viết các lớp Java, JSP & Cập nhật ứng dụng. đặc tính

Gói/Vị tríLớp/Tên giao diệnTạo/Cập nhậtPurposecom. nhà phát triển. khởi động mùa xuân. bộ điều khiểnHóa đơnBộ điều khiển. javacreateController classcom. nhà phát triển. khởi động mùa xuân. thực thểHóa đơn. lớp javacreateModel/Entity. nhà phát triển. khởi động mùa xuân. kho lưu trữHóa đơnKho lưu trữ. java tạo giao diện kho lưu trữ Com. nhà phát triển. khởi động mùa xuân. dịch vụIExcelDataDịch vụ. javacreateService Giao diện cho hoạt động DBcom. nhà phát triển. khởi động mùa xuân. dịch vụIFileUploaderDịch vụ. javacreateService Giao diện để tải lên bất kỳ filecom nào. nhà phát triển. khởi động mùa xuân. Dịch vụ. implExcelDataServiceImpl. lớp triển khai javacreateService cho DB operationcom. nhà phát triển. khởi động mùa xuân. Dịch vụ. implFileUploaderServiceImpl. lớp triển khai javacreateService để tải lên bất kỳ tệprc/main/resourcesapplication nào. propertiesupdateproperties để khai báo các thuộc tính chung trong projectrc/main/webapp/WEB-INF/pagesuploadPage. jspcreateUI để tải lên filesrc/main/webapp/WEB-INF/pagessuccess. trang jspcreateUI thành công khi dữ liệu được lưu vào cơ sở dữ liệu

Dưới đây là các mã cho mỗi tập tin

Bộ điều khiển hóa đơn. java

Bộ điều khiển hóa đơn. java

package com.dev.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dev.springboot.entity.Invoice;
import com.dev.springboot.repository.InvoiceRepository;
import com.dev.springboot.service.IExcelDataService;
import com.dev.springboot.service.IFileUploaderService;

@Controller
public class InvoiceController {

@Autowired
IFileUploaderService fileService;

@Autowired
IExcelDataService excelservice;

@Autowired
InvoiceRepository repo;

@GetMapping("/")
public String index() {
return "uploadPage";
}

@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

fileService.uploadFile(file);

redirectAttributes.addFlashAttribute("message",
"You have successfully uploaded '"+ file.getOriginalFilename()+"' !");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/";
}

@GetMapping("/saveData")
public String saveExcelData(Model model) {

List excelDataAsList = excelservice.getExcelDataAsList();
int noOfRecords = excelservice.saveExcelData(excelDataAsList);
model.addAttribute("noOfRecords",noOfRecords);
return "success";
}
}

Hóa đơn. java

Hóa đơn. java

package com.dev.springboot.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Invoice {

@Id
@GeneratedValue
private Long id;
private String name;
private Double amount;
private String number;
private String receivedDate;

public Invoice() {

}

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getReceivedDate() {
return receivedDate;
}
public void setReceivedDate(String receivedDate) {
this.receivedDate = receivedDate;
}

public Invoice(Long id, String name, Double amount, String number, String receivedDate) {
super();
this.id = id;
this.name = name;
this.amount = amount;
this.number = number;
this.receivedDate = receivedDate;
}
}

Kho lưu trữ hóa đơn. java

Lớp kho lưu trữ dưới dạng InvoiceRepository. java

package com.dev.springboot.repository;

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

import com.dev.springboot.entity.Invoice;

public interface InvoiceRepository extends JpaRepository {

}

Dịch vụ dữ liệu IExcel. java

Dịch vụ dữ liệu IExcel. java

package com.dev.springboot.service;

import java.util.List;

import com.dev.springboot.entity.Invoice;

public interface IExcelDataService {

List getExcelDataAsList();

int saveExcelData(List invoices);
}

IFileUploaderDịch Vụ. java

IFileUploaderDịch Vụ. java

package com.dev.springboot.service;

import org.springframework.web.multipart.MultipartFile;

public interface IFileUploaderService {

public void uploadFile(MultipartFile file);
}

ExcelDữ liệuDịch vụImpl. java

ExcelDữ liệuDịch vụImpl. java

package com.dev.springboot.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.EncryptedDocumentException;
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.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dev.springboot.entity.Invoice;
import com.dev.springboot.repository.InvoiceRepository;
import com.dev.springboot.service.IExcelDataService;

@Service
public class ExcelDataServiceImpl implements IExcelDataService {

@Value("${app.upload.file:${user.home}}")
public String EXCEL_FILE_PATH;

@Autowired
InvoiceRepository repo;

Workbook workbook;

public List getExcelDataAsList() {

List list = new ArrayList();

// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();

// Create the Workbook
try {
workbook = WorkbookFactory.create(new File(EXCEL_FILE_PATH));
} catch (EncryptedDocumentException | IOException e) {
e.printStackTrace();
}

// Retrieving the number of sheets in the Workbook
System.out.println("-------Workbook has '" + workbook.getNumberOfSheets() + "' Sheets-----");

// Getting the Sheet at index zero
Sheet sheet = workbook.getSheetAt(0);

// Getting number of columns in the Sheet
int noOfColumns = sheet.getRow(0).getLastCellNum();
System.out.println("-------Sheet has '"+noOfColumns+"' columns------");

// Using for-each loop to iterate over the rows and columns
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell);
list.add(cellValue);
}
}

// filling excel data and creating list as List
List invList = createList(list, noOfColumns);

// Closing the workbook
try {
workbook.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return invList;
}

private List createList(List excelData, int noOfColumns) {

ArrayList invList = new ArrayList();

int i = noOfColumns;
do {
Invoice inv = new Invoice();

inv.setName(excelData.get(i));
inv.setAmount(Double.valueOf(excelData.get(i + 1)));
inv.setNumber(excelData.get(i + 2));
inv.setReceivedDate(excelData.get(i + 3));

invList.add(inv);
i = i + (noOfColumns);

} while (i < excelData.size());
return invList;
}

@Override
public int saveExcelData(List invoices) {
invoices = repo.saveAll(invoices);
return invoices.size();
}
}

FileUploader ServiceImpl. java

FileUploader ServiceImpl. java

package com.dev.springboot.service.impl;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.dev.springboot.entity.Invoice;
import com.dev.springboot.service.IFileUploaderService;

@Service
public class FileUploaderServiceImpl implements IFileUploaderService {


public List invoiceExcelReaderService() {
return null;
}

@Value("${app.upload.dir:${user.home}}")
public String uploadDir;

public void uploadFile(MultipartFile file) {

try {
Path copyLocation = Paths
.get(uploadDir + File.separator + StringUtils.cleanPath(file.getOriginalFilename()));
Files.copy(file.getInputStream(), copyLocation, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Could not store file " + file.getOriginalFilename()
+ ". Please try again!");
}
}
}

đăng kí. đặc tính

________số 8

tải lên trang. jsp

tải lên trang. jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>




File Upload Page



File Upload & Data Save Page







Please select a file to upload :



Press here to upload the file :




${message}




Do you want to save excel data into database ? Yes     No


thành công. jsp

thành công. jsp

package com.dev.springboot.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dev.springboot.entity.Invoice;
import com.dev.springboot.repository.InvoiceRepository;
import com.dev.springboot.service.IExcelDataService;
import com.dev.springboot.service.IFileUploaderService;

@Controller
public class InvoiceController {

@Autowired
IFileUploaderService fileService;

@Autowired
IExcelDataService excelservice;

@Autowired
InvoiceRepository repo;

@GetMapping("/")
public String index() {
return "uploadPage";
}

@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

fileService.uploadFile(file);

redirectAttributes.addFlashAttribute("message",
"You have successfully uploaded '"+ file.getOriginalFilename()+"' !");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "redirect:/";
}

@GetMapping("/saveData")
public String saveExcelData(Model model) {

List excelDataAsList = excelservice.getExcelDataAsList();
int noOfRecords = excelservice.saveExcelData(excelDataAsList);
model.addAttribute("noOfRecords",noOfRecords);
return "success";
}
}
0

Khi tất cả các tệp trên được tạo trong STS, cấu trúc dự án của bạn sẽ trông giống như ảnh chụp màn hình bên dưới

Làm cách nào để đọc các giá trị từ tệp Excel và lưu trữ trong cơ sở dữ liệu trong Java?

Ví dụ đọc file excel (. xls) .
nhập java. io. Tập tin;
nhập java. io. FileInputStream;
nhập java. io. IOException;
tổ chức nhập khẩu. apache. poi. hssf. mô hình người dùng. Bảng HSSF;
tổ chức nhập khẩu. apache. poi. hssf. mô hình người dùng. Sổ tay HSSF;
tổ chức nhập khẩu. apache. poi. ss. mô hình người dùng. Tế bào;
tổ chức nhập khẩu. apache. poi. ss. mô hình người dùng. Trình đánh giá công thức;

Làm cách nào để nhập dữ liệu từ Excel vào cơ sở dữ liệu trong Java?

table_daily_report();

Java có thể đọc các tệp Excel không?

Trong Java, việc đọc tệp Excel không giống như đọc tệp Word do các ô trong tệp Excel. JDK không cung cấp API trực tiếp để đọc dữ liệu từ tệp Excel mà chúng tôi phải chuyển sang thư viện của bên thứ ba là Apache POI.

Làm cách nào để đọc dữ liệu từ trang tính Excel và chèn vào bảng cơ sở dữ liệu?

Đầu tiên, sao chép dữ liệu từ Excel rồi dán vào bảng SQL Server bằng tùy chọn menu Cơ sở dữ liệu > Bảng > Chỉnh sửa 200 hàng trên cùng. Always start by copying and pasting a single row of data to validate the data types.