使用Apache POI库,可以通过以下步骤来删除行和追加行:
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
Workbook workbook = WorkbookFactory.create(new File("path/to/excel.xlsx"));
Sheet sheet = workbook.getSheet("Sheet1");
int rowIndex = 2; // 要删除的行索引(从0开始)
sheet.removeRow(sheet.getRow(rowIndex));
int rowIndex = sheet.getLastRowNum() + 1; // 新行的索引
Row newRow = sheet.createRow(rowIndex);
Cell cell1 = newRow.createCell(0);
cell1.setCellValue("Value 1");
Cell cell2 = newRow.createCell(1);
cell2.setCellValue("Value 2");
FileOutputStream fileOut = new FileOutputStream("path/to/output.xlsx");
workbook.write(fileOut);
fileOut.close();
完整示例代码如下:
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 ApachePOIExample {
public static void main(String[] args) throws IOException {
Workbook workbook = WorkbookFactory.create(new File("path/to/excel.xlsx"));
Sheet sheet = workbook.getSheet("Sheet1");
// 删除行
int rowIndex = 2; // 要删除的行索引(从0开始)
sheet.removeRow(sheet.getRow(rowIndex));
// 追加行
rowIndex = sheet.getLastRowNum() + 1; // 新行的索引
Row newRow = sheet.createRow(rowIndex);
Cell cell1 = newRow.createCell(0);
cell1.setCellValue("Value 1");
Cell cell2 = newRow.createCell(1);
cell2.setCellValue("Value 2");
FileOutputStream fileOut = new FileOutputStream("path/to/output.xlsx");
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
请注意替换代码中的文件路径为实际的Excel文件路径。此示例使用的是xlsx文件格式,如果要处理xls文件,可以将XSSFWorkbook
替换为HSSFWorkbook
。