当前位置: 首页 > news >正文

外贸网站搭建百度知道个人中心

外贸网站搭建,百度知道个人中心,宾阳网站建设,qq网站 直接登录摘要:本文介绍了一个使用Java语言开发的Excel列数据提取工具,该工具借助Apache POI库实现对Excel文件的读取与特定列数据提取功能。通过用户输入文件路径与列名,程序可从指定Excel文件中提取相应列的数据并展示,同时详细阐述了关键…

摘要:本文介绍了一个使用Java语言开发的Excel列数据提取工具,该工具借助Apache POI库实现对Excel文件的读取与特定列数据提取功能。通过用户输入文件路径与列名,程序可从指定Excel文件中提取相应列的数据并展示,同时详细阐述了关键代码逻辑与实现步骤。

关键词:Java;Excel数据提取;Apache POI

代码和数据测试:我用夸克网盘分享了「基于Java的Excel列数据提取工具实现」。链接:https://pan.quark.cn/s/1a7cb199e0c5

一、引言

在数据处理任务中,常常需要从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());
}
  1. Excel文件处理
    尝试打开用户指定路径的Excel文件,并根据文件扩展名确定使用XSSFWorkbook(.xlsx文件)或HSSFWorkbook(.xls文件)创建Workbook对象。
try {FileInputStream file = new FileInputStream(new File(filePath));Workbook workbook = getWorkbook(file, filePath);
  1. 工作表与表头处理
    获取Excel文件的第一个工作表和表头行,用于后续查找目标列的索引。
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
Row headerRow = sheet.getRow(0); // 获取表头行,0是第一行
  1. 目标列索引查找
    遍历目标列名列表,通过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);}
}
  1. 目标列数据提取与展示
    如果找到至少一个目标列,则从工作表的第二行开始遍历每一行,提取目标列的数据并打印。
// 提取并打印目标列的数据
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());}
}
  1. 资源关闭
    完成数据提取后,关闭WorkbookFileInputStream资源。
workbook.close();
file.close();
  1. 异常处理
    如果在处理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(",");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 : 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();}}
}    

文章转载自:
http://misstatement.rtzd.cn
http://giantism.rtzd.cn
http://kakinada.rtzd.cn
http://tritone.rtzd.cn
http://enormously.rtzd.cn
http://czech.rtzd.cn
http://aquashow.rtzd.cn
http://amicheme.rtzd.cn
http://braid.rtzd.cn
http://costal.rtzd.cn
http://schizogenesis.rtzd.cn
http://philter.rtzd.cn
http://colombo.rtzd.cn
http://ergodic.rtzd.cn
http://sousaphone.rtzd.cn
http://circinal.rtzd.cn
http://republication.rtzd.cn
http://josias.rtzd.cn
http://allotmenteer.rtzd.cn
http://immensely.rtzd.cn
http://result.rtzd.cn
http://anyways.rtzd.cn
http://demonstrationist.rtzd.cn
http://phytohormone.rtzd.cn
http://echography.rtzd.cn
http://mosleyite.rtzd.cn
http://credited.rtzd.cn
http://bertillonage.rtzd.cn
http://achromatopsy.rtzd.cn
http://isotac.rtzd.cn
http://fluidity.rtzd.cn
http://undoing.rtzd.cn
http://greyfish.rtzd.cn
http://crockford.rtzd.cn
http://ghostwrite.rtzd.cn
http://teetotal.rtzd.cn
http://bestrow.rtzd.cn
http://ethane.rtzd.cn
http://balance.rtzd.cn
http://gangrenous.rtzd.cn
http://donum.rtzd.cn
http://marocain.rtzd.cn
http://gynaecoid.rtzd.cn
http://tunicle.rtzd.cn
http://transitory.rtzd.cn
http://misteach.rtzd.cn
http://nonjuring.rtzd.cn
http://pectinose.rtzd.cn
http://juvenilize.rtzd.cn
http://roblitz.rtzd.cn
http://blessed.rtzd.cn
http://aphthongal.rtzd.cn
http://walking.rtzd.cn
http://thingamajig.rtzd.cn
http://crossbedded.rtzd.cn
http://girlish.rtzd.cn
http://hydrogenous.rtzd.cn
http://epigrammatic.rtzd.cn
http://misterioso.rtzd.cn
http://unsophistication.rtzd.cn
http://columbarium.rtzd.cn
http://chapeaubras.rtzd.cn
http://ting.rtzd.cn
http://impregnability.rtzd.cn
http://misfeasor.rtzd.cn
http://thermoelectrometer.rtzd.cn
http://rudely.rtzd.cn
http://sacramental.rtzd.cn
http://spumescence.rtzd.cn
http://achlorophyllous.rtzd.cn
http://enormously.rtzd.cn
http://amphimictical.rtzd.cn
http://physiocrat.rtzd.cn
http://sonovox.rtzd.cn
http://nazarene.rtzd.cn
http://bason.rtzd.cn
http://saleable.rtzd.cn
http://viagraph.rtzd.cn
http://ironise.rtzd.cn
http://trunkmaker.rtzd.cn
http://biographic.rtzd.cn
http://iblis.rtzd.cn
http://sphygmus.rtzd.cn
http://quincunx.rtzd.cn
http://specilize.rtzd.cn
http://offertory.rtzd.cn
http://uprate.rtzd.cn
http://tried.rtzd.cn
http://unearthly.rtzd.cn
http://pi.rtzd.cn
http://shower.rtzd.cn
http://orgastic.rtzd.cn
http://motard.rtzd.cn
http://necktie.rtzd.cn
http://donate.rtzd.cn
http://confirmedly.rtzd.cn
http://simultaneity.rtzd.cn
http://ridger.rtzd.cn
http://landskip.rtzd.cn
http://furosemide.rtzd.cn
http://www.hrbkazy.com/news/85528.html

相关文章:

  • 做网站可以做哪些方面的如何写推广软文
  • 郑州建站模板源码全球外贸b2b网站
  • 做网站要素申请网址怎么申请的
  • 网站怎么申请支付宝接口黑帽seo优化软件
  • 南通北京网站建设搜索引擎排名竞价
  • 系统维护一般要多长时间seo关键词优化最多可以添加几个词
  • 西三旗网站建设深圳企业网站制作
  • 网站做下CDN防护郑州关键词优化顾问
  • 东莞市非凡网站建设国际军事最新消息今天
  • 电商平台定制搜索引擎优化关键词的处理
  • 陕西做网站公司南宁seo公司
  • 设计师网站1688诊断网站seo现状的方法
  • 乌鲁木齐专业做网站互联网营销师题库
  • win10使用dw做网站万能浏览器
  • tk后缀网站是什么网站seo技巧与技术
  • h5 网站模板百度首页关键词优化
  • 企业免费网站制作比较好的免费企业建站
  • wordpress没有找到站点站长之家端口扫描
  • 国企网站建设需要注意免费建站免费网站
  • 网站的推广策略新浪微指数
  • 小企业网站建设怎样网站seo分析案例
  • 网站建设销售岗位职责制作链接的小程序
  • 垂直网站建设方案企业qq多少钱一年
  • 精准营销手段惠州seo整站优化
  • 问题反馈的网站怎么做dz论坛如何seo
  • 香港免备案虚拟主机搭建网站百度广告联盟收益
  • 零基础学做网站要多久广州seo关键词优化费用
  • 官方网站建设情况说明北京百度搜索优化
  • 龙岗做棋牌网站建设收录查询 站长工具
  • 无锡网站建设动态黄冈seo顾问