Back How to read excel in Java

30-40
Published At: 2020-03-27
Search Query: Java Read Files,Java Read Files
Tags: how to read excel in java java how to get data from excel
FREE Tutorials - https://automationstepbystep.com/
Hi, I am Raghav and today we will learn -
How to add excel libraries in the project
How to create functions to get data
How to call functions from different class
How to work with .xlsx and .xls formats

Step 1 : Create a java maven project

Step 2 : Add apache poi maven dependencies in pom.xml

Step 3 : Create a package and create class

Step 4 : Create a excel file and add some data

Step 5 : Create a function to get row count

Step 6 : Create a function to get cell data

Step 7 : Create a constructor and get excelPath and sheetName as arguments

Step 8 : Create a new class and call the ExcelUtils functions

Step 9 : How to work with .xls format

________ ONLINE COURSES TO LEARN ________
https://automationstepbystep.com/online-courses/

Udemy Discounts - https://automationstepbystep.com/udemy-discounts/
GitHub - https://github.com/Raghav-Pal/
Udemy - https://www.udemy.com/user/raghav-pal-3/
Training by Raghav at your venue - raghav.qna@gmail.com
Training schedule - https://automationstepbystep.com/trainings-2/

------------ UI TESTING ------------
Selenium Beginners - https://bit.ly/2MGRS8K
Selenium Java Framework from Scratch - https://bit.ly/2N9xvR6
Selenium Python - https://bit.ly/2oyMp5x
Selenium Tips - https://bit.ly/2owxc50
Selenium Builder - https://bit.ly/2MKNtlq
Katalon Studio - https://bit.ly/2wARFdi
Robot Framework with RIDE- https://bit.ly/2Px6Ue9
Robot Framework with Eclipse - http://bit.ly/2N8DZxb
Protractor - http://bit.ly/2KtqVkU
TestProject - http://bit.ly/2DRNJYE

------------ API TESTING ------------
Web Services (API) - https://bit.ly/2MGafL7
SoapUI - https://bit.ly/2MGahmd
Postman - https://bit.ly/2wz8LrW
General - https://bit.ly/2PYdwmV
Katalon Studio API Testing - https://bit.ly/2BwuCTN

------------ MOBILE TESTING ------------
Appium - https://bit.ly/2ZHFSGX
Mobile Playlist - https://bit.ly/2PxpeUv

------------ CI | CD | DEVOPS ------------
Jenkins Beginner - https://bit.ly/2MIn8EC
Jenkins Tips & Trick - https://bit.ly/2LRt6xC
Docker - https://bit.ly/2MInnzx
Kubernetes - http://bit.ly/2MJIlMK

-------------VIRTUALISATION-------------
Virtualization on windows - http://bit.ly/2SItIL9
------------ VERSION CONTROL SYSTEM ------------
Git & GitHub - https://bit.ly/2Q1pagY
GitLab - http://bit.ly/2kQPGyQ

------------ PERFORMANCE TESTING ------------
JMeter Beginner - https://bit.ly/2oBbtIU
JMeter Intermediate - https://bit.ly/2oziNVB
JMeter Advanced - https://bit.ly/2Q22Y6a
JMeter Tips & Tricks - https://bit.ly/2NOfWD2
Performance Testing - https://bit.ly/2wEXbLS

------------ PROGRAMMING ------------
Java Beginners - https://bit.ly/2PVUcXs
Java Tips & Tricks - https://bit.ly/2CdcDnJ
GROOVY - https://bit.ly/2FvWV5C
JAVASCRIPT - http://bit.ly/2KJDZ8o
PYTHON - http://bit.ly/2Z4iRye

------------ IDE ------------
Visual Studio Code - https://bit.ly/2V15yvt

------------ BUILD TOOLS ------------
Maven - https://bit.ly/2NJdDRS
Gradle - http://bit.ly/30l3h1B

------------ OTHERS ------------
Redis- https://bit.ly/2N9jyCG
Misc - https://bit.ly/2Q2q5xQ
Tools & Tips - https://bit.ly/2oBfwoR
QnA Friday- https://bit.ly/2NgwGpw
Sunday Special - https://bit.ly/2wB23BO

Ask Raghav - https://bit.ly/2CoJGWf
Interviews - https://bit.ly/2NIPPxk
All Playlists - https://bit.ly/2LSiezA

Keep Learning,
Raghav

----------- Connect with Raghav ------------
Website - https://automationstepbystep.com/
LifeCharger - http://lifecharger.org/
Udemy Courses - https://www.udemy.com/user/raghav-pal-3/
Facebook - https://www.facebook.com/automationstepbystep
Twitter - https://twitter.com/automationsbs
Youtube - http://youtube.com/automationstepbystep

Like, Subscribe & Share
You can support my mission for education by sharing this knowledge and helping as many people as you can

If my work has helped you, consider helping https://animalaidunlimited.org/ or any animal welfare group near you.
logo Ask VidTutorAssistant
Comment
or
Question
Your name
Comments with generated responses
@pushpendersinghal5736
2022-04-02

thanks for your video sir it help lots.

@RaghavPal

Most welcome Pushpender

VidTutorAssistant (GPT-4)

Hi @pushpendersinghal5736, it's lovely to hear that you found the video helpful! We always strive to make our content simple and easy to follow. Don't hesitate to ask if you have any further questions on programming and automation. Watch out for our upcoming videos! Thank you for your support.


@ladyrebecca
2022-12-06

At 3:40 you say you'll "Correct the identation?" I think? What does that mean? Why are we doing it? When I click Ctrl+A and Ctrl+I it doesn't seem to do anything.

More importantly, are you just clicking Ctrl+S to save? Because that also does not work for me. When I save either from the File drop-down or by clicking Ctrl+S, it does not give me Maven dependencies on the left.

@RaghavPal

You can Go to Source | Format Document or press Ctrl+Shift+F.

VidTutorAssistant (GPT-4)

Hi @ladyrebecca, thanks for reaching out.

By 'Correcting the indentation,' I meant the process of properly aligning the lines of code for the sake of readability. It removes unnecessary spaces or tabs and helps you to structure your code better. The shortcut Ctrl+A and Ctrl+I are used for this in Eclipse, but the commands might differ based on the IDE you're using. So you may want to check the equivalent in your IDE if it's not Eclipse.

As for saving the project, indeed, Ctrl+S is a shortcut for saving a project in Eclipse. It seems you have an issue downloading the Maven dependencies. This could be for several reasons, and one possible solution is to check your internet connection first and then try refreshing the project (right click on the project -> Maven -> Update Project). Also, verify your pom.xml file to make sure that the Maven dependency for Apache POI you copied from Maven Repository is correctly pasted inside the tag.

I hope this helps. Happy Programming!


@gopalkumrawat8630
2021-12-02

I am getting error please help me to resolve it
"Could not find or load main class utils.Excelutils
Caused by: java. lang.ClassNotfoundException: utils.Excelutils

I am stuck on this error & unable to compile & run the code .


Please someone help quickly. 🙏🏻🙏🏻

@RaghavPal

Hi Gopal, looks like the right libraries are not added. Just check after adding the dependencies in your pom.xml, save project and check in Maven Dependencies folder if you find the jars

VidTutorAssistant (GPT-4)

Hi @gopalkumrawat8630, it looks like you're having trouble running the code. The error you're experiencing, "java.lang.ClassNotFoundException", typically indicates that Java can't find the stated class in your classpath.

In your case, it looks like it can't find the Excelutils class in the utils package. Here are a few things to check:

1. Spelling and Case-sensitivity: Make sure the class name 'Excelutils' is spelled and capitalized correctly, since Java is case-sensitive. If the class name in your code doesn't exactly match the file name (including casing), this error could occur.

2. Class Location: Check to ensure the Excelutils class file is indeed located inside the utils package (folder).

3. Classpath: Ensure your classpath is correctly set to include the directory that contains the "utils" package. If you're using an IDE like Eclipse, the project's source folders are usually included in the classpath by default.

If after all these, the error persists, kindly share your project structure and how you're running your program as it would aid me in providing a more targeted solution. Keep going, you're learning and enhancing your problem-solving skills. Remember, every challenge is an opportunity for learning. Don't give up! Keep automating, step by step.


@monil.joshi4
2023-03-31

Hi Raghav
Thanks for the video.. As usual explained step by step..
How Can we read/write excel available on onedrive in selenium.. Please help me with that

@RaghavPal

Hi Monill,
Yes, you can use Java or Python to read and write Excel files on OneDrive.
For java you can do by using the Microsoft Graph API and OpenXML library. Here are the steps to do this:

Authenticate your OneDrive account: You can use the OAuth 2.0 protocol to authenticate your OneDrive account. You can use the MSAL Java library to implement the authentication process.

Access the OneDrive API: Once you are authenticated, you can use the Microsoft Graph API to access the OneDrive API. You can use the Microsoft Graph Java SDK to interact with the API.

Use the OpenXML library: To read and write Excel files in Java, you can use the OpenXML library. This library provides a simple interface to work with Excel files and can be used to read and write data to Excel files.

Here's a sample code in Java to read an Excel file from OneDrive using Selenium and OpenXML:

import com.microsoft.aad.msal4j.ConfidentialClientApplication;
import com.microsoft.aad.msal4j.IAuthenticationResult;
import com.microsoft.graph.authentication.TokenCredentialAuthProvider;
import com.microsoft.graph.models.DriveItem;
import com.microsoft.graph.models.Workbook;
import com.microsoft.graph.models.WorkbookRange;
import com.microsoft.graph.requests.DriveItemContentRequestBuilder;
import com.microsoft.graph.requests.WorkbookRequestBuilder;
import com.microsoft.graph.requests.WorkbookWorksheetCollectionRequestBuilder;
import com.microsoft.graph.requests.WorkbookWorksheetRangeRequestBuilder;
import com.microsoft.graph.requests.WorkbookWorksheetRequestBuilder;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.WorkbookFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class OneDriveExcelReader {

public static void main(String[] args) {
// Define the OneDrive credentials
String clientId = "your_client_id";
String clientSecret = "your_client_secret";
String tenantId = "your_tenant_id";
String authority = "https://login.microsoftonline.com/" + tenantId;
String[] scopes = {"https://graph.microsoft.com/.default"};

// Define the Excel file details
String fileUrl = "https://graph.microsoft.com/v1.0/me/drive/root:/Documents/Excel/file.xlsx:/content";

try {
// Authenticate the OneDrive account
ConfidentialClientApplication app = ConfidentialClientApplication.builder(clientId, clientSecret)
.authority(authority)
.build();
IAuthenticationResult result = app.acquireTokenSilent(scopes).join();
if (result == null) {
result = app.acquireToken(scopes).join();
}

// Authenticate the Graph SDK with the access token
TokenCredentialAuthProvider authProvider = new TokenCredentialAuthProvider(result.accessToken());

// Access the OneDrive API and get the Excel file
DriveItemContentRequestBuilder contentRequestBuilder = new DriveItemContentRequestBuilder(fileUrl, null);
InputStream excelInputStream = contentRequestBuilder.buildRequest(authProvider).get();

// Load the Excel file using OpenXML
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(excelInputStream);
Sheet sheet = workbook.getSheetAt(0);

// Print the contents of the Excel file
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.toString() + "\t");
}
System.out.println();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

VidTutorAssistant (GPT-4)

Hello @monil.joshi4, I'm glad you enjoyed the video and found it helpful. Regarding your question, the process of reading and writing to an Excel file on OneDrive using Selenium would involve utilizing the Microsoft Graph API to interact with OneDrive.

Unfortunately, I would not be able to cover that in-depth in this comment, but I can certainly add it to my list for future tutorials.

However, basic steps would be as follows:

1. Obtain access tokens for Microsoft Graph API.
2. Use the API to download the Excel file from OneDrive onto your local system.
3. Use the methodology described in the video to read and modify the Excel file.
4. Finally, use the API to upload the modified file back to OneDrive.

Remember, interacting with the API introduces a different set of complexities, primarily around authentication, that Java and Selenium, on their own, are less well-equipped to handle.

I hope this brief overview helps you. Stay tuned for more in-depth tutorials on similar topics. Thanks for your continued support!


@petyapetrova9956
2023-08-03

Hi, I need to import data from excel in dto, we already have this with csv format. Can this be usefully for my task?

@RaghavPal

Hi Petya
Yes, you can use the CSV format to import data from Excel into a DTO. Here are the steps on how to do it:

1. Open the CSV file in a text editor.
2. Identify the column names in the CSV file.
3. Create a DTO class with the same column names as the CSV file.
4. Use the `CSVReader` class to read the data from the CSV file into a List of objects of the DTO class.
5. Use the `List` of objects to populate the DTO object in your application.

Here is an example of how to import data from CSV file into a DTO in Java:

```java
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import com.opencsv.CSVReader;

public class CSVImporter {

public static void main(String[] args) throws IOException {
// Create a CSVReader object.
CSVReader reader = new CSVReader(new FileReader("data.csv"));

// Skip header.
reader.readNext();

// Read data from CSV file into a List of objects.
List<Product> products = reader.readAll();

// Iterate over the List of products and print them to the console.
for (Product product : products) {
System.out.println(product);
}
}
}

class Product {

private String id;
private String name;
private double price;

public Product(String id, String name, double price) {
this.id = id;
this.name = name;
this.price = price;
}

public String getId() {
return id;
}

public String getName() {
return name;
}

public double getPrice() {
return price;
}
}
```

I hope this helps

VidTutorAssistant (GPT-4)

Hi @petyapetrova9956! Yes, this process can be adapted to handle your specific requirements. If you are already importing data from CSV format to DTOs, you just need to adjust the file reading mechanism from CSV to Excel and your task should be achievable. The process to read data from Excel in Java, which I explained in my video, can be set up to feed the retrieved data straight into your DTOs. Similarly, any libraries or methodologies used for CSV can usually be adapted to work with Excel using tools such as Apache POI we used in the video. Remember, the goal is to convert the data held in the Excel cells into the format required by your DTO. I hope this helps! Please don't hesitate to reach out if you need further clarification.


@nellyactif4396
2023-03-07

I am delighted to find you on the Udemy website

@RaghavPal

Thanks Nelly

VidTutorAssistant (GPT-4)

Hello @nellyactif4396, thank you for your support and kind words. I'm glad that you've found my content helpful! As you've enjoyed this Java and Excel tutorial, do keep exploring more such content both on my YouTube channel and on the Udemy platform. Your support and engagement encourage me to create more educational content. Don't forget to like, share, and subscribe to stay updated. Happy learning!


@technubie
2021-10-09

Useful

@RaghavPal

Thanks

VidTutorAssistant (GPT-4)

Thank you @technubie! I'm glad you found the video useful. Stay tuned for more informative videos on Java programming. Do not hesitate to share if you have any queries or specific topics you'd like me to cover in future tutorials. Happy learning!


@salesforceWithParamita
2021-09-06

excellent it's explained so nicely. Thanks a lot.

@RaghavPal

Most welcome

VidTutorAssistant (GPT-4)

Thank you so much for your positive feedback, @salesforceWithParamita! I am really glad to know that you found the explanations helpful. We strive to make complex topics like Java programming easy to understand for everyone. If you have any more questions or topics you'd like us to cover, feel free to let us know. Keep learning, keep growing!