基于Java实现Excel列数据提取工具
目录
- 一、引言
- 二、核心代码实现
- 2.1 主函数逻辑
- 2.2 获取Workbook对象
- 2.3 查找列索引
- 2.4 获取单元格值字符串
- 三、完整代码
一、引言
在数据处理任务中,常常需要从Excel文件中提取特定列的数据。本程序利用Java语言和Apache POI库,实现根据用户输入的列名,从Excel文件中提取对应列数据的功能。
- 支持处理.xls 和.xlsx 两种 Excel 格式文件
- 通过命令行交互获取文件路径和要提取的列名
- 可以同时提取多个列的数据
- 对列名进行了大小写不敏感的匹配
- 包含了基本的错误处理机制
二、核心代码实现
使用的依赖
<dependencies> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>5.2.3</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooXML</artifactId> <version>5.2.3</version> </dependency> </dependencies>
2.1 主函数逻辑
主函数main负责与用户交互并协调整个数据提取流程。
1.用户输入获取:
使用Scanner类获取用户输入的Excel文件路径和要提取的列名。用户输入的列名以逗号分隔,程序将其分割并处理为目标列名列表。
Scanner scanner = new Scanner(System.in); System.out.print("请输入Excel文件路径: "); String filePath = scanner.nextLine(); System.out.print("请输入要提取的列名(多个列名用逗号分隔): "); String columnNamesInput = scanner.nextLine(); String[] columnNames = columnNamesInput.split(","); List<String> targetColumnNames = new ArrayList<>(); for (String name : columnNames) { targetColumnNames.add(name.trim()); }
2.Excel文件处理:
尝试打开用户指定路径的Excel文件,并根据文件扩展名确定使用XSSFWorkbook(.xlsx文件)或HSSFWorkbook(.xls文件)创建Workbook对象。
try { FileInputStream file = new FileInputStream(new File(filePath)); Workbook workbook = getWorkbook(file, filePath);
3.工作表与表头处理:
获取Excel文件的第一个工作表和表头行,用于后续查找目标列的索引。
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 Row headerRow = sheet.getRow(0); // 获取表头行,0是第一行
4.目标列索引查找:
遍历目标列名列表,通过findColumnIndex方法查找每个列名在表头中的索引位置,并记录找到的索引。
// 查找目标列的索引 List<Integer> targetColumnIndices = new ArrayList<>(); for (String targetName : targetColumnNames) { int columnIndex = findColumnIndex(headerRow, targetName); if (columnIndex != -1) { targetColumnIndices.add(columnIndex); System.out.println("找到列: " + targetName + ", 索引: " + columnIndex); } else { System.out.println("未找到列: " + targetName); } }
5.目标列数据提取与展示:
如果找到至少一个目标列,则从工作表的第二行开始遍历每一行,提取目标列的数据并打印。
// 提取并打印目标列的数据 if (!targetColumnIndices.isEmpty()) { System.out.println("\n提取的数据:"); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) continue; StringBuilder rowData = new StringBuilder(); for (int colIndex : targetColumnIndices) { Cell cell = row.getCell(colIndex); if (cell != null) { rowData.append(getCellValueAsString(cell)).append("\t"); } else { rowData.append("null\t"); } } System.out.println(rowData.toString().trim()); } }
6.资源关闭:
完成数据提取后,关闭Workbook和FileInputStream资源。
workbook.close(); file.close();
7.异常处理:
如果在处理Excel文件过程中发生IOException,捕获异常并打印错误信息。
catch (IOException e) { System.err.println("处理Excel文件时出错: " + e.getMessage()); e.printStackTrace(); }
2.2 获取Workbook对象
getWorkbook方法根据文件路径的扩展名,返回对应的Workbook对象。如果文件扩展名不是.xlsx或.xls,则抛出IllegalArgumentException异常。
private static Workbook getWorkbook(FileInputStream file, String filePath) throws IOException { if (filePath.endsWith(".xlsx")) { return new XSSFWorkbook(file); } else if (filePath.endsWith(".xls")) { return new HSSFWorkbook(file); } else { throw new IllegalArgumentException("不支持的文件格式: " + filePath); } }
2.3 查找列索引
findColumnIndex方法在给定的表头行中查找指定列名的索引。它遍历表头行的每个单元格,比较单元格的字符串值(忽略大小写)与目标列名,若匹配则返回该单元格的索引,否则返回 -1。
private static int findColumnIndex(Row headerRow, String columnName) { if (headerRow == null) return -1; for (int i = 0; i <= headerRow.getLastCellNum(); i++) { Cell cell = headerRow.getCell(i); if (cell != null && cell.getCellType() == CellType.STRING) { String cellValue = cell.getStringCellValue().trim(); if (cellValue.equalsIgnoreCase(columnName)) { return i; } } } return -1; }
2.4 获取单元格值字符串
getCellValueAsString方法根据单元格的类型,将单元格的值转换为字符串形式返回。它支持处理字符串、数字、日期、布尔值、公式和空白等不同类型的单元格。
private static String getCellValueAsString(Cell cell) { CellType cellType = cell.getCellType(); switch (cellType) { case STRING: return cell.getStringCellValue(); case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue().jstoString(); } else { return String.valueOf(cell.getNumericCellValue()); } case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: return cell.getCellFormula(); case BLANK: return ""; default: return cell.toString(); } }
结果输出:
请输入Excel文件路径: D:\pyprogect\excellianxi\all.xlsx
请输入要提取的列名(多个列名用逗号分隔): id,age,income找到列: id, 索引: 0找到列: age, 索引: 1找到列: income, 索引: 4提取的数据:ID12101 48.0 17546.0ID12102 40.0 30085.1ID12103 51.0 16575.4ID12104 23.0 20375.4ID12105 57.0 50576.3ID12106 57.0 37869.6ID12107 22.0 8877.07ID12678 34.0 17546.0ID12679&nbpythonsp; 35.0 30085.1ID12680 36.0 16575.4ID12681 37.0 20375.4ID12682 38.0 50576.3ID12683 39.0 37869.6ID12684 40.0 8877.07Process finished with exit code 0
三、完整代码
package org.example; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ExcelColumnSelector { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入Excel文件路径: "); String filePath = scanner.nextLine(); System.out.print("请输入要提取的列名(多个列名用逗号分隔): "); String columnNamesInput = scanner.nextLine(); String[] columnNames = columnNamesInput.split(","); List<String> targetColumnNames = new ArrayList<>(); for (String name : columnNames) { targetColumnNames.add(name.trim()); } try { FileInputStream file = new FileInputStream(new File(filePath)); Workbook workbook = getWorkbook(file, filePath); Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 Row headerRow = sheet.getRow(0); // 获取表头行 // 查找目标列的索引 List<Integer> targetColumnIndices = new ArrayList<>(); for (String targetName : targeandroidtColumnNames) { int columnIndex = findColumnIndex(headerRow, targetName); if (columnIndex != -1) { targetColumnIndices.add(columnIndex); System.out.println("找到列: " + targetName + ", 索引: " + columnIndex); } else { System.out.println("未找到列: " + targetName); } } // 提取并打印目标列的数据 if (!targetColumnIndices.isEmpty()) { System.out.println("\n提取的数据:"); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row == null) continue; StringBuilder rowData = new StringBuilder(); for (int colIndex : targetColumnIndices) { Cell cell = row.getCell(colIndex); if (cell != null) { rowData.append(getCellValueAsString(cell)).append("\t"); } else { rowData.append("null\t"); } } System.out.println(rowData.toString().trim()); } } workbook.close(); file.close(); } catch (IOException e) { System.err.println("处理Excel文件时出错: " + e.getMessage()); e.printStackTrace(); } } private static Workbook getWorkbook(FileInputStream file, String filePath) throws IOException { if (fijslePath.endsWith(".xlsx")) { return new XSSFWorkbook(file); } else if android(filePath.endsWith(".xls")) { return new HSSFWorkbook(file); } else { throw new IllegalArgumentException("不支持的文件格式: " + filePath); } } private static int findColumnIndex(Row headerRow, String columnName) { if (headerRow == null) return -1; for (int i = 0; i <= headerRow.getLastCellNum(); i++) { Cell cell = headerRow.getCell(i); if (cell != null && cell.getCellType() == CellType.STRING) { String cellValue = cell.getStringCellValue().trim(); if (cellValue.equalsIgnoreCase(columnName)) { return i; } } } return -1; } private static String getCellValueAsString(Cell cell) { CellType cellType = cell.getCellType(); switch (cellType) { case STRING: return cell.getStringCellValue(); case NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { return cell.getDateCellValue().toString(); } else { return String.valueOf(cell.getNumericCellValue()); } case BOOLEAN: return String.valueOf(cell.getBooleanCellValue()); case FORMULA: return cell.getCellFormula(); case BLANK: return ""; default: return cell.toString(); } } }
到此这篇关于基于Java实现Excel列数据提取工具的文章就介绍到这了,更多相关Java提取Excel列数据内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!
精彩评论