Java 使用 Apache POI 删除 Excel 文件中的空白行 - 代码示例
Java 使用 Apache POI 删除 Excel 文件中的空白行 - 代码示例\n\n要删除 Excel 文件中的空白行,可以使用 Apache POI 库来操作 Excel 文件。以下是一个示例代码,说明如何使用 POI 库来删除空白行。\n\n首先,需要添加 POI 库的依赖。可以在 Maven 项目中的 pom.xml 文件中添加以下依赖:\n\nxml\n<dependency>\n <groupId>org.apache.poi</groupId>\n <artifactId>poi</artifactId>\n <version>4.1.0</version>\n</dependency>\n\n<dependency>\n <groupId>org.apache.poi</groupId>\n <artifactId>poi-ooxml</artifactId>\n <version>4.1.0</version>\n</dependency>\n\n\n然后,可以使用以下代码来删除 Excel 文件中的空白行:\n\njava\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport org.apache.poi.ss.usermodel.*;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\n\npublic class RemoveBlankRows {\n public static void main(String[] args) {\n try {\n FileInputStream file = new FileInputStream("input.xlsx");\n Workbook workbook = new XSSFWorkbook(file);\n Sheet sheet = workbook.getSheetAt(0);\n \n for (int i = sheet.getLastRowNum(); i >= 0; i--) {\n Row row = sheet.getRow(i);\n if (isEmptyRow(row)) {\n sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);\n }\n }\n \n file.close();\n \n FileOutputStream outFile = new FileOutputStream("output.xlsx");\n workbook.write(outFile);\n outFile.close();\n \n System.out.println("Blank rows removed successfully.");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n \n private static boolean isEmptyRow(Row row) {\n if (row == null) {\n return true;\n }\n \n for (Cell cell : row) {\n if (cell.getCellType() != CellType.BLANK) {\n return false;\n }\n }\n \n return true;\n }\n}\n\n\n请注意,上述代码假设要处理的 Excel 文件名为 "input.xlsx",并将处理结果保存为 "output.xlsx"。你需要根据实际情况修改这些文件名。\n\n此代码会打开 Excel 文件,遍历每一行并检查是否为空白行。如果是空白行,则使用 shiftRows 方法将该行及其以下的行向上移动一行。最后,将处理结果写入新的 Excel 文件中。\n\n希望对你有所帮助!
原文地址: https://www.cveoy.top/t/topic/pAri 著作权归作者所有。请勿转载和采集!