java 删除excel 空行和空列
要删除Excel中的空行和空列,可以使用Apache POI库。以下是使用POI库在Java中删除空行和空列的示例代码:
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;
public class ExcelUtils {
public static void removeEmptyRowsAndColumns(String inputFile, String outputFile) throws IOException {
FileInputStream fis = new FileInputStream(inputFile);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
// 删除空行
for (int i = sheet.getLastRowNum(); i >= sheet.getFirstRowNum(); i--) {
Row row = sheet.getRow(i);
if (rowIsEmpty(row)) {
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
}
}
// 删除空列
for (int i = sheet.getLastRowNum(); i >= 0; i--) {
Row row = sheet.getRow(i);
int lastCellNum = row.getLastCellNum();
for (int j = lastCellNum - 1; j >= 0; j--) {
Cell cell = row.getCell(j);
if (cellIsEmpty(cell)) {
row.shiftCells(j + 1, lastCellNum, -1);
}
}
}
FileOutputStream fos = new FileOutputStream(outputFile);
workbook.write(fos);
workbook.close();
fis.close();
fos.close();
}
private static boolean rowIsEmpty(Row row) {
if (row == null || row.getLastCellNum() <= 0) {
return true;
}
for (int i = row.getFirstCellNum(); i < row.getLastCellNum(); i++) {
Cell cell = row.getCell(i, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell != null && cell.getCellType() != CellType.BLANK) {
return false;
}
}
return true;
}
private static boolean cellIsEmpty(Cell cell) {
return (cell == null || cell.getCellType() == CellType.BLANK);
}
public static void main(String[] args) {
try {
removeEmptyRowsAndColumns("input.xlsx", "output.xlsx");
System.out.println("Empty rows and columns have been removed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述代码使用removeEmptyRowsAndColumns方法从输入文件中读取Excel数据,删除空行和空列,然后将结果写入输出文件。可以将输入文件和输出文件的路径作为参数传递给removeEmptyRowsAndColumns方法。
请注意,此代码仅适用于XLSX格式的Excel文件。如果要处理XLS格式的文件,需要相应地更改Workbook的实例化方法
原文地址: https://www.cveoy.top/t/topic/hP1l 著作权归作者所有。请勿转载和采集!