You are here
Home > java >

How to read Excel file in Java Spring Boot and upload into Database?

How to read excel file in java spring boot and upload into database ?Many clients provide their data in the form of excel sheet and request developer to save it in your database as it is. If you ever have implemented ‘How to read Excel file in Java Spring Boot and upload into Database?’, it’s good. If not, no worries!, we will learn the same in this article. In the end, you will find it very easy & fast way to get it done. In fact, once you go through the complete article you will observe that you only need to provide the location of your excel file in file. You will get the data uploaded into database by making small changes in your own entity classes only.

We will not promote any hard-coding in our implementation. Even if you are working first time in Spring Boot application, you will easily implement the functionality by following the steps mentioned here. Further to escape hard-coding we will take some of the values from properties file so that we don’t need to modify the java file in case we have any change request in future. Also, we will use the most popular Apache POI: ‘The Java API for Microsoft Documents’ in our implementation. Now let’s get into the topic “How to read Excel file in Java Spring Boot and upload into Database?”.

What all functionality/features will you get from this article?

1) How to save data into the database if input data is in the form of excel sheet.
2) How to upload any file (apart from excel) using a web browser.
3) Above two functionalities are not interdependent. We can execute each functionality separately.
4) Apache POI Latest version (currently 4.1.2) has been used to implement the project.
5) Additionally, code is successfully tested on JDK8, JDK9 and even JDK14 versions.
6) How to read Excel file in Java Spring Boot and upload into Database?

What will you learn after implementing this application?

1) How to create a Spring Boot web application that incorporates industry level project design?

2) How to design a Java web application, including all layers using Controller, Service, Repository, UI etc. as in real time project designs?

3) Equally important, Where and how to use Annotations like @Value, @Autowired, @Controller, @Service, @Repository, @Entity, @Id, @GeneratedValue, @GetMapping, @PostMapping etc.

4) Also, Working with Spring Boot Data JPA repository interface.

5) Implementation of the most popular Apache POI (Java API for Microsoft Documents)

6) Then, How to work with file?

7) How to upload data as a batch into database using Spring Boot?

8) Additionally, How to write modular & reusable code?

9) How to implement dynamic code with minimal changes, keeping future change requests in mind?

10) How to write code without hard-coding the values using Spring Boot?

11) Last but not the least, you will learn “How to Upload Excel data into Database Using Spring Boot”.

12) Particularly, How to read Excel file in Java Spring Boot and upload into Database?.

What all implementations can you do yourself after going through this example?

1) How to read data from excel sheet and insert into database table in spring mvc?

2) How to upload excel file to database using spring boot?

3) spring boot excel file upload example

4) How to read data from excel sheet and insert into database table in spring boot?

5) How to import data from excel to mysql using spring boot?

6) How to upload excel file into database using java?

7) How to read excel file in spring boot example?

8) How to read data from excel and store in the datatable in java?

9) How to upload and read excel file in spring boot?

10) How to write java code to read excel file and insert into database?

11) How to import excel data into database using java?

12) How to upload Excel file into database using Apache POI and Spring Framework?

Software Used in this project

♦ STS (Spring Tool Suite): Version-> 4.7.1. RELEASE
⇒ Dependent Starters : Spring Web, Spring Data JPA, MySql Driver
♦ MySQL Database : Version ->8.0.19 MySQL Community Server
♦ JDK8 or later versions (Extremely tested on JDK8, JDK9 and JDK14)

External Dependencies

We will add following apache ‘poi-ooxml’ dependency in pom.xml as it is an external jar to get the features of Microsoft Excel.



You should have a database ready to store data from excel file. If not, create a MySQL database to save the data. Still, if you just want to test the functionality you can use our configurations as database name ‘exceldata’ and table name ‘invoice’ accordingly.

Coding Steps on ‘How to read Excel file in Java Spring Boot and upload into Database?’

— Create Project in STS

If you are new in Spring Boot go to Internal Link to create a sample project in spring boot. While creating a project in STS, add 3 starters ‘MySql Driver’, ‘Spring Data JPA‘ and ‘Spring Web’. You can also add ‘Spring Boot DevTools’ optionally.

Where to place JSP files ?

In order to accommodate JSP files,

1) create folder ‘webapps’ under src/main/
2) under ‘webapps’ create folder ‘WEB-INF’
3) Under ‘WEB-INF’ create folder ‘pages’ to accommodate your JSP files as view part.
4) Now your Folder structure hierarchy should look like “src/main/webapps/WEB-INF/pages”.

— Writing Java classes, JSPs & Updating

Package/LocationClass/Interface nameCreate/UpdatePurpose class class Interface Interface for DB operations Interface to upload any file implementation class for DB operations implementation class to upload any file
src/main/resourcesapplication.propertiesupdateproperties file to declare common properties in the project
src/main/webapp/WEB-INF/pagesuploadPage.jspcreateUI page to upload a file
src/main/webapp/WEB-INF/pagessuccess.jspcreateUI page to success message when data is saved into database

Below are the codes for each file

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;


public class InvoiceController {

IFileUploaderService fileService;

IExcelDataService excelservice;

InvoiceRepository repo;

public String index() {
return "uploadPage";

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


"You have successfully uploaded '"+ file.getOriginalFilename()+"' !");
try {
} catch (InterruptedException e) {
// TODO Auto-generated catch block
return "redirect:/";

public String saveExcelData(Model model) {

List<Invoice> excelDataAsList = excelservice.getExcelDataAsList();
int noOfRecords = excelservice.saveExcelData(excelDataAsList);
return "success";

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

public class Invoice {

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) { = id;
public String getName() {
return name;
public void setName(String 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(); = id; = name;
this.amount = amount;
this.number = number;
this.receivedDate = receivedDate;

Repository class as



public interface InvoiceRepository extends JpaRepository<Invoice, Long> {


import java.util.List;


public interface IExcelDataService {

List<Invoice> getExcelDataAsList();

int saveExcelData(List<Invoice> invoices);

import org.springframework.web.multipart.MultipartFile;

public interface IFileUploaderService {

public void uploadFile(MultipartFile file);

import java.util.ArrayList;
import java.util.List;

import org.apache.poi.EncryptedDocumentException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


public class ExcelDataServiceImpl implements IExcelDataService {

public String EXCEL_FILE_PATH;

InvoiceRepository repo;

Workbook workbook;

public List<Invoice> getExcelDataAsList() {

List<String> list = new ArrayList<String>();

// 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) {

// 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);

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

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

return invList;

private List<Invoice> createList(List<String> excelData, int noOfColumns) {

ArrayList<Invoice> invList = new ArrayList<Invoice>();

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

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

i = i + (noOfColumns);

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

public int saveExcelData(List<Invoice> invoices) {
invoices = repo.saveAll(invoices);
return invoices.size();

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;


public class FileUploaderServiceImpl implements IFileUploaderService {

public List<Invoice> invoiceExcelReaderService() {
return null;

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) {
throw new RuntimeException("Could not store file " + file.getOriginalFilename()
+ ". Please try again!");

#DB Connection Properties

# Data JPA Properties

# MVC view properties

# upload file 

# Excel file as input for storing it's data


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html>
<meta charset="ISO-8859-1">
<title>File Upload Page</title>

<h2>File Upload & Data Save Page</h2>

<form action ="uploadFile" method = "POST" enctype = "multipart/form-data">
<br /> <br />
Please select a file to upload :
<input type = "file" name = "file" value = "Browse File" /> <br /> <br />
Press here to upload the file :
<input type = "submit" value = "upload" /> <br /> <br />

<h4 style="color: green">${message}</h4> <br />

Do you want to save excel data into database ? <a href="saveData"><b>Yes</b></a> &nbsp &nbsp <a href="/"><b>No</b></a>


<%@ page contentType = "text/html; charset = UTF-8" %>
<title>Data Save Example</title>

<b> Total ${noOfRecords} records uploaded !</b>

Once all above files created in STS, your project structure should look something like below screenshot:



Running application

In order to run the application, right click on Project, then select Run As >> Spring Boot App.

Testing Results

Finally, to test the results paste url in your browser : http://localhost:8080/
Accordingly, you should see the below page :



Furthermore, in order to upload an excel file, click on ‘Choose File’ which will browse to your file system, then select an excel file to be uploaded and click ‘OK/Open’. Now click on upload in order to upload the file at the location you provided in accordingly. Note: Besides excel files, this functionality will also work for any file having other extensions. Consequently, once the file is uploaded, you will see the success message with file name you uploaded as below.

How to Upload Excel data into Database Using Spring Boot ?

In order to upload excel records into database click on ‘Yes’ link. Consequently, you will see the success page immediately with number of records uploaded into database. On the other hand, if you click no, nothing will happen, it will just redirect to the same page.


Uploading Excel data into Database Using Spring Boot

Furthermore, you can check the saved records into database as below:


♥ Note: If you provide the input file name as a value of ‘app.upload.file’ in and put the excel file in the same folder, You can directly save the excel records into database just by clicking on the ‘Yes’ link. In this case, Even You don’t have to upload the file.

How to do our own implementation from this Example with minimal changes?

In fact, you need to change values of properties included in the file
1) Update the values of first 4 properties according to your database
2) Also update the file storage directory path in the value of property ‘app.upload.dir’
3) Then update the upload file path with file name in the value of property ‘app.upload.file’

Moreover, Below are the changes in java files :
4) To store excel records into database you need to create new Entity class, new Repository class in place of ‘’ & ‘’ accordingly as per your requirements.
5) Consequently, you need to change all the occurrences of entity class name in ‘’ and ‘’. It’s ‘Invoice’ in our case.
6) In addition, you need to update entity class method names in createList() method of ‘’.

Can we use this implementation in a real project ?

Of course, you can use this implementation in a real project with modification described above as per your requirement.

What are the changes we need to do if we want to use this functionality in our real project?

You can go through the minimal modifications suggested in the above FAQ section ‘How to do our own implementation from this Example with minimal changes?’ of this article accordingly.


After going through all the points mentioned in the article, You should be able to work on ‘How to read data from excel sheet and insert into database table in spring boot ?’. However, If you follow all the steps as mentioned in the article, you will implement it successfully in one go without facing any issue. Additionally, you will also be able to work on ‘How to upload any file (apart from excel) using web browser’ confidently. Now, we can expect from you to apply this knowledge in your real time project whenever you have such kind of requirement. Furthermore, if you face any issue on running this project, don’t hesitate to put your comments below.

♥ Also, if you want to learn how to generate PDF report using Spring Boot, kindly visit our separate article on ‘How to generate dynamic PDF report using Spring Boot‘. Additionally, if you want to learn more on Spring Boot trending topics kindly visit our Spring Boot Section.

8 thoughts on “How to read Excel file in Java Spring Boot and upload into Database?

  1. hey !
    Thanks your tutorial has been very useful during my project work .I just have one doubt …..My fields are not inserted at correct place .Could you help me with that?

  2. Hello,

    Many thanks for this great guide on how to upload excel data into a db. I follow it through it work perfectly.

    Could you kindly also explain, or point me to an example of, how to do the same using Spring WebFlux instead of spring web?

  3. Thanks Davinder Sir,

    I Always learn new things from your posts.
    What I like most is you give information with proofs and working code.

    Thanks for sharing these valuable contents

  4. It took too much time to load if i clicked yes after uploaded the file and did not return any result
    ..can anyone plss help me out ..

Leave a Reply