Update or edit existing Excel files in Java using Apache POI

Requirement -Programatically update an Excel spreadsheet in Java.

Solutions – Here an example of Apache POI to update a XLS workbook. Apache POI is a very good API , that can be handy in manipulating Excel documents.This tutorial focuses on XLS documents (Office 97 – 2003).

The existing excel file like below –

sdsdsdsdsdsdsd

Below is code to update the excel file

import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import java.util.Iterator;
public class updateExcels {  

        public static void main(String[] args) throws Exception{
                
                FileInputStream fsIP= new FileInputStream(new File("C:\\TechartifactExcel.xls")); //Read the spreadsheet that needs to be updated
                 
                HSSFWorkbook wb = new HSSFWorkbook(fsIP); //Access the workbook
                 
                HSSFSheet worksheet = wb.getSheetAt(0); //Access the worksheet, so that we can update / modify it.
                 
                Cell cell = null; // declare a Cell object
               
                cell = worksheet.getRow(2).getCell(2);   // Access the second cell in second row to update the value
                 
                cell.setCellValue("OverRide Last Name");  // Get current cell value value and overwrite the value
                 
                fsIP.close(); //Close the InputStream
                
                FileOutputStream output_file =new FileOutputStream(new File("C:\\TechartifactExcel.xls"));  //Open FileOutputStream to write updates
                 
                wb.write(output_file); //write changes
                 
                output_file.close();  //close the stream    
        }
}

after updating excel file would look like below –

1updateexcel2

happy coding with Vinay in techartifact ….

Write an excel file in java using Apache POI

Requirment – How to write an excel file in Java

Solutions– Well Apache POI is answer.This API will help you a lot.you have to download and add the POI JAR file to your project’s class path. The Apache POI JAR file can be found http://poi.apache.org/download.html

Following is code –

public static void main(String[] args) throws IOException {
     
    // Directory path where the xls file will be created
    String filePath = "C:/Vinay/ApachePoi/VinayExcel.xls";
    FileOutputStream fout = new FileOutputStream(filePath );
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    HSSFWorkbook workBook = new HSSFWorkbook();
 
    // Create the spreadsheet
    HSSFSheet spreadSheet = workBook.createSheet("vinay_sheet");
     
    // Create the first row
    HSSFRow row = spreadSheet.createRow((short) 0);
     
    // Create the cells and write to the file
    HSSFCell cell;
     
    cell = row.createCell(0);
    cell.setCellValue(new HSSFRichTextString("Vinay"));
    cell = row.createCell(1);
    cell.setCellValue(new HSSFRichTextString("Kumar"));
     
    workBook.write(outputStream);
     
    outputStream.writeTo(fout);
    outputStream.close();
    fout.close();
}

Happy coding with Vinay in techartifact

Read Excel file using Apache POI in Java

Requirment – How to read an excel file in Java

Solutions– Well Apache POI is answer.This API will help you a lot.you have to download and add the POI JAR file to your project’s class path. The Apache POI JAR file can be found http://poi.apache.org/download.html
Please note

HSSF (Horrible SpreadSheet Format) – reads and writes Microsoft Excel (XLS) format files.
XSSF (XML SpreadSheet Format) – reads and writes Office Open XML (XLSX) format files.

Following snippet we will use

//..
FileInputStream file = new FileInputStream(new File("C:\\VinayTest.xls"));
             
//Get the workbook instance for XLS file 
HSSFWorkbook workbook = new HSSFWorkbook(file);
 
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
 
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
 
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();

Following is code to read from excel file

public static void main(String[] args) throws IOException {
         
        // Location of the source file
        String sourceFilePath = "C:/Vinay/ApachePoi/TestFile.xls";
         
        FileInputStream fileInputStream = null;
         
        // Array List to store the excel sheet data
        List excelData = new ArrayList();
         
        try {
             
            // FileInputStream to read the excel file
            fileInputStream = new FileInputStream(sourceFilePath);
  
            // Create an excel workbook
            HSSFWorkbook excelWorkBook = new HSSFWorkbook(fileInputStream);
             
            // Retrieve the first sheet of the workbook.
            HSSFSheet excelSheet = excelWorkBook.getSheetAt(0);
  
            // Iterate through the sheet rows and cells. 
            // Store the retrieved data in an arrayList
            Iterator rows = excelSheet.rowIterator();
            while (rows.hasNext()) {
                HSSFRow row = (HSSFRow) rows.next();
                Iterator cells = row.cellIterator();
  
                List cellData = new ArrayList();
                while (cells.hasNext()) {
                    HSSFCell cell = (HSSFCell) cells.next();
                    cellData.add(cell);
                }
  
                excelData .add(cellData);
            }
             
            // Print retrieved data to the console
            for (int rowNum = 0; rowNum < excelData.size(); rowNum++) {
                 
                List list = (List) excelData.get(rowNum);
                 
                for (int cellNum = 0; cellNum < list.size(); cellNum++) {
                     
                    HSSFCell cell = (HSSFCell) list.get(cellNum);
                     
                    if(cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
                        System.out.print(cell.getRichStringCellValue().getString() + " ");
                    } else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
                        System.out.print(cell.getNumericCellValue() + " ");
                    } else if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {
                        System.out.println(cell.getBooleanCellValue() + " ");
                    }
                }
                System.out.println("");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }
}}

Happy coding with Vinay in techartifact