Creating and Managing Excel Files using Java

    package demo;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Readwrite {

    public static void main(String[] args) throws Exception
    {

         //Get the excel file and create an input stream for excel
         FileInputStream fis = new FileInputStream("D:\\Testing_Team\\Age_Validation.xlsx");

         //load the input stream to a workbook object
         //Use XSSF for (.xlsx) excel file and HSSF for (.xls) excel file
         XSSFWorkbook wb = new XSSFWorkbook(fis);

         //get the sheet from the workbook by index
         XSSFSheet sheet = wb.getSheet("Age");

         //Count the total number of rows present in the sheet

             int rowcount = sheet.getLastRowNum();
             System.out.println(" Total number of rows present in the sheet : "+rowcount);





         //get column count present in the sheet
         int colcount = sheet.getRow(1).getLastCellNum();
         System.out.println(" Total number of columns present in the sheet : "+colcount);

         //get the data from sheet by iterating through cells
         //by using for loop
         for(int i = 1; i<=rowcount; i++)
          {
             XSSFCell cell = sheet.getRow(i).getCell(1);
             String celltext="";

             //Get celltype values
             if(cell.getCellType()==Cell.CELL_TYPE_STRING)
             {
                 celltext=cell.getStringCellValue();
             }
             else if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC)
             {
                  celltext=String.valueOf(cell.getNumericCellValue());
             }
             else if(cell.getCellType()==Cell.CELL_TYPE_BLANK)
             {
                 celltext="";
             }

          //Check the age and set the Cell value into excel
             if(Double.parseDouble(celltext)>=18)
             {
                 sheet.getRow(i).getCell(2).setCellValue("Major");
             }
             else
             {
                 sheet.getRow(i).getCell(2).setCellValue("Minor");
             }

          }//End of for loop

         //close the file input stream
         fis.close();


    //Open an excel to write the data into workbook
    FileOutputStream fos = new FileOutputStream("D:\\Testing_Team\\Age_Validation.xlsx");

    //Write into workbook
    wb.write(fos);

    //close fileoutstream
    fos.close();

    }

}

*Facing an issue as follows: [ Exception in thread "main" java.lang.NullPointerException at demo.Readwrite.main(Readwrite.java:31) ] . Can you provide some guidance on this matter?

I found this helpful video reference: https://www.youtube.com/watch?v=orYZB_RUgNc

I have included both poi-ooxml and poi dependencies.

Awaiting your valuable response.*

Answer №1

Your comment suggests that you should use index numbers instead of column names, It appears that 'Age' is a column name in your sheet.

 //retrieve the sheet from the workbook using an index
         XSSFSheet sheet = wb.getSheetAt(0);

Please update the above line in your code and execute it.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

FileDetector feature in Selenium for Java RemoteWebDriver

I'm encountering an issue with file uploads using Selenium's RemoteWebDriver (specifically the Chrome driver, set up with Selenium Grid). A problem similar to the one discussed in this thread: Sending Keys to Input WebElement fails as it is not ...

Identify the CSS Framework being used in conjunction with Selenium

I have developed a program that crawls through various web pages and conducts tests using Selenium. My current task is to identify which CSS Frameworks are utilized on these websites for statistical analysis. Currently, I am using the FireFox Webdriver to ...

Attempting to navigate a menu by hovering over it and selecting a link from the sub-menu, only to be met with unsuccessful results

I'm currently practicing how to hover over a menu and then click on a link in the sub-menu. For this exercise, I need to visit the URL "", hover over "Hello Sign in", and finally click on the link labeled "Start here". I've managed to successfu ...

What is the best way to avoid the "/" character when using send_keys?

When running a script that writes code into a textarea on a website, I encountered an issue. The first four lines were being written correctly until var url = "https:, at which point the cursor would jump to the upper left of the text area before continuin ...

Executing Tasks in Kubernetes

As I work on developing a scraping app using multiple Selenium scripts that are interdependent, I've realized the potential benefits of utilizing Kubernetes for this project. However, in order to make this setup successful, I need to establish communi ...

Is there a way to choose an item from a dropdown menu in Selenium using Python if the option's element is not clickable?

I am encountering an issue while trying to select an item from the dropdown menu. The options that I need to choose from are not selectable and display an alert message stating, "Alert: This element is not interactable through selenium(automation) as it is ...

Ways to showcase a response in a subsequent activity

Currently, I'm developing a search module in my application. I previously asked for guidance on how to display JSON response in another activity (reference). I have successfully sent a request to the server and received a response containing some dat ...

Personalized Jasmine matchers for a Protractor/WebDriverJS component

Greetings fellow developers, I'm looking to create a custom matcher for Protractor/WebDriverJS element. Can anyone assist in improving my current code? Here is what I aim to include in the specs files: var button = element(by.tagName('button&a ...

Strategies for addressing the issue: SessionNotCreatedException occurs when a new session cannot be initiated. This error may be due to an incorrect remote server address

Hi everyone, I'm completely new to using Appium and testing in general. I'm currently experiencing an error that I am unsure how to resolve. Any help would be greatly appreciated. My goal is to test an application on my android studio emulator, ...

Encountering a java.lang.ExceptionInInitializerError when attempting to execute the Tests class due to an issue with cucumber.deps.com.thoughtworks.xstream.XStream.setup

Check out this dropbox link for further investigation. Encountered an issue while trying to run a test scenario in IntelliJ, resulting in java.lang.ExceptionInInitializerError at the first step. The StepDefinition class is provided below: package automatio ...

Locate element by xpath in Python with the help of Selenium WebDriver

Is it possible to locate these elements using xpath? <a class="single_like_button btn3-wrap" onclick="openFbLWin_2224175();"> <span>&nbsp;</span><div class="btn3">Like</div></a> and <button value="1" class="_42 ...

By default in Excel, the value "TRUE" is recognized as a boolean "TRUE", causing a failure in my selenium code

I have a situation in my Excel Input where one of the cell values is "true". By default, Excel interprets this as "TRUE" - a boolean value. Even after trying to handle this in my code by using .toString(), it still fails to work properly. Are there any p ...

Error messages cannot be dismissed in RobotFramework if the element does not exist

test cases using robotFramework: confirm that a user is able to send a request and be redirected to the next page Wait until element is enabled ${errorCodeMessage} Element Text Should Be ${errorCodeMessage} Vikailmoituksen tapahtumat ou ...

Attempting to extract data from a webpage by utilizing Selenium in a newly opened tab

Recently, I successfully utilized Selenium to launch a webpage in a new tab on my Chrome browser. The webpage is loaded with a huge table of valuable data that I need to extract using Beautiful Soup. However, when attempting to execute my code, the followi ...

Interference from Modal Overlay Disrupts functionality of other Links on Shared Page

My primary webpage consists of multiple links, including one that triggers a modal when clicked on. This modal opens on top of the main page, allowing me to compare expected and actual links. However, I encounter difficulty in comparing the rest of the lin ...

Webdriver Selenium 2

What is the process for creating a batch file to run Selenium Webdriver projects in Java? I have successfully created executable jar files by using File > Export > Java > Runnable Jar, but I am interested in creating a BATCH File. Any assistance would be ...

Switch the type and version of the browser using Selenium

In an attempt to change my user agent using the Selenium Webdriver, I have utilized the following code. However, it has come to my attention that Google Analytics is able to easily detect my browser and its version (specifically Firefox 54.0 in this case). ...

Encountering difficulties with resolving captcha through a specific service

Utilizing a somewhat hardcoded approach, I extract the site-key with confidence due to its consistent length. Following that, I make use of the 2captcha API Documentation to send a POST request for the captcha token retrieval. However, I encounter two sign ...

What is the best way to automate the crawling process without the need to input any specific numbers or codes

I have developed a Python script using Selenium for scraping restaurant names from a webpage. The script is working well when I manually input the number of entries to parse. The webpage uses lazy-loading to display 40 names with each scroll, but my scri ...

Having trouble fetching website data using Selenium in Python

I'm encountering an issue when attempting to extract a table from a dynamic webpage using selenium in Python. Here is the code snippet I am currently using: from selenium import webdriver url = 'https://draft.shgn.com/nfc/public/dp/788/grid&apos ...