Java easyexcel 删除空列和行
要删除空列和行,您可以使用EasyExcel库中的Sheet对象的方法来实现。以下是一个示例代码,演示如何删除空列和行:
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import java.util.List;
public class DeleteEmptyColumnsAndRowsExample {
public static void main(String[] args) {
String fileName = "path/to/your/excel/file.xlsx";
// 读取Excel文件
List<List<Object>> dataList = EasyExcel.read(fileName).sheet().doReadSync();
// 删除空列
deleteEmptyColumns(dataList);
// 删除空行
deleteEmptyRows(dataList);
// 写入Excel文件
ExcelWriterBuilder writerBuilder = EasyExcel.write(fileName);
ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet();
for (List<Object> dataRow : dataList) {
sheetBuilder.row(dataRow);
}
sheetBuilder.doWrite();
}
private static void deleteEmptyColumns(List<List<Object>> dataList) {
int rowCount = dataList.size();
if (rowCount > 0) {
int columnCount = dataList.get(0).size();
for (int columnIndex = columnCount - 1; columnIndex >= 0; columnIndex--) {
boolean isEmptyColumn = true;
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
List<Object> dataRow = dataList.get(rowIndex);
if (dataRow.size() > columnIndex && dataRow.get(columnIndex) != null) {
isEmptyColumn = false;
break;
}
}
if (isEmptyColumn) {
for (int rowIndex = 0; rowIndex < rowCount; rowIndex++) {
List<Object> dataRow = dataList.get(rowIndex);
if (dataRow.size() > columnIndex) {
dataRow.remove(columnIndex);
}
}
}
}
}
}
private static void deleteEmptyRows(List<List<Object>> dataList) {
int rowCount = dataList.size();
if (rowCount > 0) {
int columnCount = dataList.get(0).size();
for (int rowIndex = rowCount - 1; rowIndex >= 0; rowIndex--) {
boolean isEmptyRow = true;
List<Object> dataRow = dataList.get(rowIndex);
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
if (dataRow.size() > columnIndex && dataRow.get(columnIndex) != null) {
isEmptyRow = false;
break;
}
}
if (isEmptyRow) {
dataList.remove(rowIndex);
}
}
}
}
}
请注意,这只是一个示例代码。您需要根据您的实际需求进行相应的修改和适配。此示例代码假设您要删除的空列和行都是连续的,并且没有任何合并单元格。如果您的情况不同,请根据需要进行相应的更改
原文地址: https://www.cveoy.top/t/topic/hPlW 著作权归作者所有。请勿转载和采集!