How to use the XSSFRow class to insert and delete cell objects
To insert and delete cell objects using the XSSFRow class, you need to first create an XSSFWorkbook object and load an Excel file, then obtain the corresponding table sheet and row row.
Firstly, before using the XSSFRow class for insertion and deletion, it is necessary to add the Apache POI dependency in the pom.xml file:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
Next, let's assume we have an Excel file called "example. xlsx", which contains a table called "Sheet1". In this table, we have the following data:
|A | B | C|
|-------|------|------|
|1 | 2 | 3|
|4 | 5 | 6|
|7 | 8 | 9|
Prepare another sample Java code:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ExcelManipulation {
public static void main(String[] args) {
try {
//Load Excel file
FileInputStream file = new FileInputStream("example.xlsx");
Workbook workbook = new XSSFWorkbook(file);
//Obtain the table sheet (assuming we choose the first sheet)
Sheet sheet = workbook.getSheetAt(0);
//Insert Cells
InsertCell (sheet, 1, 1, "10")// Insert a cell with a value of 10 in the second row and second column
//Delete Cells
DeleteCell (sheet, 2, 2)// Delete cells from row 3 and column 3
//Save the modified Excel file
FileOutputStream outFile = new FileOutputStream("example.xlsx");
workbook.write(outFile);
//Close file stream
outFile.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Insert Cells
public static void insertCell(Sheet sheet, int rowNum, int colNum, String value) {
Row row = sheet.getRow(rowNum);
if (row == null) {
row = sheet.createRow(rowNum);
}
Cell cell = row.createCell(colNum);
cell.setCellValue(value);
}
//Delete Cells
public static void deleteCell(Sheet sheet, int rowNum, int colNum) {
Row row = sheet.getRow(rowNum);
if (row != null) {
Cell cell = row.getCell(colNum);
if (cell != null) {
row.removeCell(cell);
}
}
}
}
In this example, we loaded an Excel file called "example. xlsx", inserted a cell with a value of 10 on the first sheet, and deleted the cells in the third row and third column. Finally, we save the modified Excel file.
Please note that the Excel file path here is relative to the directory where the Java code is located. The key to the entire process is to use classes provided by Apache POI such as XSSFWorkbook, Sheet, Row, and Cell to manipulate cells in Excel files.