0% found this document useful (0 votes)
2 views

Gmail - Read and Write Excel

The document provides a comprehensive guide on reading and writing Excel files in Java using Apache POI. It explains the use of WorkbookFactory for handling both .xls and .xlsx formats, including code examples for reading data from an Excel file and writing data to a new or existing Excel file. Key methods and practices for efficient Excel file manipulation are highlighted, emphasizing the benefits of format flexibility and cleaner code.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Gmail - Read and Write Excel

The document provides a comprehensive guide on reading and writing Excel files in Java using Apache POI. It explains the use of WorkbookFactory for handling both .xls and .xlsx formats, including code examples for reading data from an Excel file and writing data to a new or existing Excel file. Key methods and practices for efficient Excel file manipulation are highlighted, emphasizing the benefits of format flexibility and cleaner code.

Uploaded by

Nagasai Maddula
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Read and write excel

1 message

Nagasai Maddula <[email protected]> Sun, 19 Jan, 2025 at 15:34


To: Nagasai Maddula <[email protected]>

Using WorkbookFactory in Apache POI is a good practice because it allows you to seamlessly handle both .xls and .xlsx formats without
worrying about the specific file type. WorkbookFactory automatically detects whether the file is in the older Excel format (.xls) or the newer
format (.xlsx) and provides the appropriate Workbook implementation (HSSFWorkbook for .xls and XSSFWorkbook for .xlsx).

Steps to Read Data from Excel using WorkbookFactory

1. Add Apache POI Dependency If you haven’t already, add the Apache POI dependency to your project (either in pom.xml for Maven or
build.gradle for Gradle).

For Maven:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>

For Gradle:

dependencies {
implementation 'org.apache.poi:poi-ooxml:5.2.3'
}

2. Java Program Using WorkbookFactory

Here’s how you can use WorkbookFactory to read data from an Excel file:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ExcelReader {


public static void main(String[] args) {
// Define the path to the Excel file
String filePath = "path_to_your_excel_file.xlsx";

try (FileInputStream fis = new FileInputStream(new File(filePath))) {


// Create a Workbook instance using WorkbookFactory
Workbook workbook = WorkbookFactory.create(fis);

// Get the first sheet from the workbook


Sheet sheet = workbook.getSheetAt(0);

// Iterate through rows and cells


for (Row row : sheet) {
for (Cell cell : row) {
// Check the cell type and read data accordingly
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
System.out.print("UNKNOWN\t");
}
}
System.out.println(); // New line for each row
}

// Close the workbook


workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation of Code:

1. FileInputStream:

Opens the Excel file using FileInputStream.


The FileInputStream is used to read the file as a stream of bytes.

2. WorkbookFactory.create():

WorkbookFactory.create() automatically detects whether the Excel file is .xls or .xlsx and creates the appropriate Workbook
object (either HSSFWorkbook for .xls or XSSFWorkbook for .xlsx).
This method is the recommended way to handle Excel files as it abstracts away the need to manually check file extensions.

3. Iterating Through Rows and Cells:

Sheet: Represents a single sheet in the Excel file.


Row: Represents a row in the sheet.
Cell: Represents a cell in the row.
The program reads each cell's value based on its type (string, numeric, or boolean) and prints it to the console.

4. Closing Resources:

The Workbook is closed using workbook.close() to release the resources associated with the file.

When to Use WorkbookFactory:

File Format Agnostic: The WorkbookFactory is especially useful when you don’t know whether the Excel file is .xls or .xlsx, or when you
want to support both formats without writing separate logic for each.
Simplified Code: It simplifies the code by removing the need to manually handle the different types of Excel file formats (HSSFWorkbook vs.
XSSFWorkbook).

Example Excel Sheet:

Example Output:

John 25.0 USA


Alice 30.0 UK
Bob 22.0 Canada

Advantages of Using WorkbookFactory:

Format Flexibility: Handles both .xls and .xlsx formats without the need for file-specific logic.
Cleaner Code: Makes the code cleaner and more maintainable by abstracting the complexity of Excel file handling.

Conclusion:

Using WorkbookFactory is a recommended approach for reading Excel files in Java as it provides a unified and efficient way to handle both .xls
and .xlsx files without additional conditional checks for file types. This simplifies the process of working with Excel files in Java.

WRITE

Writing data to an Excel file in Java is also handled efficiently by Apache POI. Just as reading data from Excel files requires Workbook and Sheet,
writing data to Excel follows a similar approach. You can write to both .xls (HSSF) and .xlsx (XSSF) formats, but Apache POI provides a
convenient method for handling both formats with the WorkbookFactory class.

Below, I'll show you how to write data to Excel using Apache POI.

Steps to Write to Excel

1. Add Apache POI Dependency Ensure the Apache POI dependency is added to your project (similar to reading data).

For Maven:

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.3</version>
</dependency>

For Gradle:

dependencies {
implementation 'org.apache.poi:poi-ooxml:5.2.3'
}
2. Java Program to Write Data to Excel:

Here is an example program that writes data to an Excel file:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelWriter {


public static void main(String[] args) {
// Create a workbook instance for .xlsx format
Workbook workbook = new XSSFWorkbook();

// Create a sheet named "Sheet1"


Sheet sheet = workbook.createSheet("Sheet1");

// Create a row (row index starts from 0)


Row row = sheet.createRow(0);

// Create cells and set values (cell index starts from 0)


Cell cell1 = row.createCell(0);
cell1.setCellValue("Name");

Cell cell2 = row.createCell(1);


cell2.setCellValue("Age");

Cell cell3 = row.createCell(2);


cell3.setCellValue("Country");

// Adding more rows with data


Row row2 = sheet.createRow(1);
row2.createCell(0).setCellValue("John");
row2.createCell(1).setCellValue(25);
row2.createCell(2).setCellValue("USA");

Row row3 = sheet.createRow(2);


row3.createCell(0).setCellValue("Alice");
row3.createCell(1).setCellValue(30);
row3.createCell(2).setCellValue("UK");

Row row4 = sheet.createRow(3);


row4.createCell(0).setCellValue("Bob");
row4.createCell(1).setCellValue(22);
row4.createCell(2).setCellValue("Canada");

// Write the data to an Excel file


try (FileOutputStream fileOut = new FileOutputStream(new File("output_excel_file.xlsx"))) {
workbook.write(fileOut);
System.out.println("Excel file written successfully!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Explanation of Code:

Workbook (XSSFWorkbook): Represents the Excel file. We use XSSFWorkbook for .xlsx files (Excel 2007+). If you are working with .xls
files, you can use HSSFWorkbook.
Sheet: Represents a sheet in the workbook. In the example above, we create a sheet called "Sheet1".
Row: Represents a row within the sheet. We create rows with index starting from 0.
Cell: Represents a single cell within a row. You can set a cell’s value using setCellValue(), which allows setting different data types (e.g.,
String, Integer, Double, etc.).

Steps in the Code:

1. Create Workbook: We create an instance of XSSFWorkbook, which is used for .xlsx format files.
2. Create Sheet: The createSheet() method creates a new sheet in the workbook.
3. Create Rows and Cells: We use createRow() to create rows and createCell() to create cells within the row. For each cell, we use
setCellValue() to insert data (String, numeric, or other types).
4. Write to File: We use FileOutputStream to specify the file path where the Excel file will be saved. The workbook.write(fileOut)
method writes the data to the specified file.

Handling Different Formats:

For .xlsx format (Excel 2007 and later): Use XSSFWorkbook.


For .xls format (Excel 2003 and earlier): Use HSSFWorkbook.

If you want to make the code format-agnostic (to handle both .xls and .xlsx formats), you can use WorkbookFactory, similar to how we did
while reading data:

Using WorkbookFactory for Writing (Format-Agnostic):

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class ExcelWriter {


public static void main(String[] args) {
try (Workbook workbook = WorkbookFactory.create(true)) { // Create a new workbook
Sheet sheet = workbook.createSheet("Sheet1");

Row row1 = sheet.createRow(0);


row1.createCell(0).setCellValue("Name");
row1.createCell(1).setCellValue("Age");

Row row2 = sheet.createRow(1);


row2.createCell(0).setCellValue("John");
row2.createCell(1).setCellValue(25);

try (FileOutputStream fileOut = new FileOutputStream(new File("output_excel_file.xlsx"))) {


workbook.write(fileOut);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

Write to Excel in Multiple Scenarios (Appending Data, Writing Multiple Sheets, etc.)

Append Data to an Existing Excel File:

If you want to add data to an existing Excel file instead of overwriting it, you'll need to open the existing workbook and append rows:

FileInputStream fis = new FileInputStream("existing_file.xlsx");


Workbook workbook = WorkbookFactory.create(fis);
Sheet sheet = workbook.getSheetAt(0); // Get the first sheet
Row newRow = sheet.createRow(sheet.getPhysicalNumberOfRows()); // Add a new row at the end

newRow.createCell(0).setCellValue("New Name");
newRow.createCell(1).setCellValue(35);

// Write back to the same file


try (FileOutputStream fileOut = new FileOutputStream("existing_file.xlsx")) {
workbook.write(fileOut);
}
workbook.close();

Write Data to Multiple Sheets:

Workbook workbook = new XSSFWorkbook();

// Creating the first sheet


Sheet sheet1 = workbook.createSheet("Sheet1");
sheet1.createRow(0).createCell(0).setCellValue("Data 1");

// Creating the second sheet


Sheet sheet2 = workbook.createSheet("Sheet2");
sheet2.createRow(0).createCell(0).setCellValue("Data 2");

FileOutputStream fileOut = new FileOutputStream("multi_sheet_excel.xlsx");


workbook.write(fileOut);
fileOut.close();
workbook.close();

Common Methods for Writing:

1. createSheet() – Creates a new sheet in the workbook.


2. createRow() – Creates a new row in the sheet.
3. createCell() – Creates a new cell within a row.
4. setCellValue() – Sets the value of a cell.
5. write(FileOutputStream fileOut) – Writes the data to the specified file output stream.
6. close() – Closes the workbook and stream to release resources.

Conclusion:
Writing to Excel files in Java is simplified with Apache POI. You can use XSSFWorkbook for .xlsx files and HSSFWorkbook for .xls files.
WorkbookFactory can also be used to handle multiple formats seamlessly. The key methods for writing data include creating sheets, rows, cells,
and using setCellValue() to assign data to cells.

You might also like