网站开发美工的任务,导航网站教程,重庆网站建设推广优化,网页制作模板的网站element摘要#xff1a;本文介绍了一个使用Java语言开发的Excel列数据提取工具#xff0c;该工具借助Apache POI库实现对Excel文件的读取与特定列数据提取功能。通过用户输入文件路径与列名#xff0c;程序可从指定Excel文件中提取相应列的数据并展示#xff0c;同时详细阐述了关键…摘要本文介绍了一个使用Java语言开发的Excel列数据提取工具该工具借助Apache POI库实现对Excel文件的读取与特定列数据提取功能。通过用户输入文件路径与列名程序可从指定Excel文件中提取相应列的数据并展示同时详细阐述了关键代码逻辑与实现步骤。
关键词JavaExcel数据提取Apache POI 代码和数据测试我用夸克网盘分享了「基于Java的Excel列数据提取工具实现」。链接https://pan.quark.cn/s/1a7cb199e0c5 一、引言
在数据处理任务中常常需要从Excel文件中提取特定列的数据。本程序利用Java语言和Apache POI库实现根据用户输入的列名从Excel文件中提取对应列数据的功能。 支持处理.xls 和.xlsx 两种 Excel 格式文件 通过命令行交互获取文件路径和要提取的列名 可以同时提取多个列的数据 对列名进行了大小写不敏感的匹配 包含了基本的错误处理机制 二、核心代码实现
使用的依赖
dependenciesdependencygroupIdorg.apache.poi/groupIdartifactIdpoi/artifactIdversion5.2.3/version/dependencydependencygroupIdorg.apache.poi/groupIdartifactIdpoi-ooxml/artifactIdversion5.2.3/version/dependency
/dependencies2.1 主函数逻辑
主函数main负责与用户交互并协调整个数据提取流程。
用户输入获取 使用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(,);ListString targetColumnNames new ArrayList();
for (String name : columnNames) {targetColumnNames.add(name.trim());
}Excel文件处理 尝试打开用户指定路径的Excel文件并根据文件扩展名确定使用XSSFWorkbook.xlsx文件或HSSFWorkbook.xls文件创建Workbook对象。
try {FileInputStream file new FileInputStream(new File(filePath));Workbook workbook getWorkbook(file, filePath);工作表与表头处理 获取Excel文件的第一个工作表和表头行用于后续查找目标列的索引。
Sheet sheet workbook.getSheetAt(0); // 获取第一个工作表
Row headerRow sheet.getRow(0); // 获取表头行0是第一行目标列索引查找 遍历目标列名列表通过findColumnIndex方法查找每个列名在表头中的索引位置并记录找到的索引。
// 查找目标列的索引
ListInteger 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);}
}目标列数据提取与展示 如果找到至少一个目标列则从工作表的第二行开始遍历每一行提取目标列的数据并打印。
// 提取并打印目标列的数据
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和FileInputStream资源。
workbook.close();
file.close();异常处理 如果在处理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().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();}
}结果输出
请输入Excel文件路径: D:\pyprogect\excellianxi\all.xlsx
请输入要提取的列名(多个列名用逗号分隔): id,age,income
找到列: id, 索引: 0
找到列: age, 索引: 1
找到列: income, 索引: 4提取的数据:
ID12101 48.0 17546.0
ID12102 40.0 30085.1
ID12103 51.0 16575.4
ID12104 23.0 20375.4
ID12105 57.0 50576.3
ID12106 57.0 37869.6
ID12107 22.0 8877.07
ID12678 34.0 17546.0
ID12679 35.0 30085.1
ID12680 36.0 16575.4
ID12681 37.0 20375.4
ID12682 38.0 50576.3
ID12683 39.0 37869.6
ID12684 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(,);ListString 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); // 获取表头行// 查找目标列的索引ListInteger 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);}}// 提取并打印目标列的数据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 (filePath.endsWith(.xlsx)) {return new XSSFWorkbook(file);} else if (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();}}
}