代码 只能清空数据,不能删除行
public class MainTest {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("test.xlsx") );
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet = wb.getSheetAt(0);
sheet.removeRow(sheet.getRow(3));
File outWB = new File("testResult.xlsx");
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
System.exit(0);
}
}
删除合并单元格
public static void removeMergedRegion(Sheet sheet, int row , int column)
{
int sheetMergeCount = sheet.getNumMergedRegions();
int index = 0;
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if(row >= firstRow && row <= lastRow)
{
if(column >= firstColumn && column <= lastColumn)
{
index = i;
}
}
}
sheet.removeMergedRegion(index);
}
本地·测试代码
package com.dxy.demo_05_08.study.excelread;
import com.ibm.icu.impl.Row;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
public class ScExcel {
public static void main(String[] args) throws Exception {
File file = new File("E:\\other\\0526.xlsx");
if (!file.exists()) {
throw new Exception("文件不存在!");
}
InputStream in = new FileInputStream(file);
XSSFWorkbook sheets = new XSSFWorkbook(in);
XSSFSheet sheetAt = sheets.getSheetAt(0);
sheetAt.removeRow(sheetAt.getRow(0));
for (int i = 0; i < sheetAt.getRow(2).getPhysicalNumberOfCells(); i++) {
removeMergedRegion(sheetAt, 0, i);
}
sheetAt.getRow(1).getCell(0).setCellValue("地市");
File outWB = new File("E:\\other\\052622.xlsx");
OutputStream out = new FileOutputStream(outWB);
sheets.write(out);
out.flush();
out.close();
}
public static void removeMergedRegion(XSSFSheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
int index = 0;
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
index = i;
}
}
}
sheet.removeMergedRegion(index);
}
}
参考文章 poi操作excel之删除模版的合并行
https://blog.csdn.net/ITarmi/article/details/123775069