Gmail - Read and Write Excel
Gmail - Read and Write Excel
1 message
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).
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'
}
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;
1. FileInputStream:
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.
4. Closing Resources:
The Workbook is closed using workbook.close() to release the resources associated with the file.
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 Output:
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.
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:
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;
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.).
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.
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:
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;
Write to Excel in Multiple Scenarios (Appending Data, Writing Multiple Sheets, etc.)
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:
newRow.createCell(0).setCellValue("New Name");
newRow.createCell(1).setCellValue(35);
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.