基于Java實(shí)現(xiàn)Excel列數(shù)據(jù)提取工具
一、引言
在數(shù)據(jù)處理任務(wù)中,常常需要從Excel文件中提取特定列的數(shù)據(jù)。本程序利用Java語言和Apache POI庫,實(shí)現(xiàn)根據(jù)用戶輸入的列名,從Excel文件中提取對應(yīng)列數(shù)據(jù)的功能。
- 支持處理.xls 和.xlsx 兩種 Excel 格式文件
- 通過命令行交互獲取文件路徑和要提取的列名
- 可以同時提取多個列的數(shù)據(jù)
- 對列名進(jìn)行了大小寫不敏感的匹配
- 包含了基本的錯誤處理機(jī)制
二、核心代碼實(shí)現(xiàn)
使用的依賴
<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 主函數(shù)邏輯
主函數(shù)main負(fù)責(zé)與用戶交互并協(xié)調(diào)整個數(shù)據(jù)提取流程。
1.用戶輸入獲?。?/p>
使用Scanner類獲取用戶輸入的Excel文件路徑和要提取的列名。用戶輸入的列名以逗號分隔,程序?qū)⑵浞指畈⑻幚頌槟繕?biāo)列名列表。
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文件,并根據(jù)文件擴(kuò)展名確定使用XSSFWorkbook(.xlsx文件)或HSSFWorkbook(.xls文件)創(chuàng)建Workbook對象。
try {
FileInputStream file = new FileInputStream(new File(filePath));
Workbook workbook = getWorkbook(file, filePath);
3.工作表與表頭處理:
獲取Excel文件的第一個工作表和表頭行,用于后續(xù)查找目標(biāo)列的索引。
Sheet sheet = workbook.getSheetAt(0); // 獲取第一個工作表 Row headerRow = sheet.getRow(0); // 獲取表頭行,0是第一行
4.目標(biāo)列索引查找:
遍歷目標(biāo)列名列表,通過findColumnIndex方法查找每個列名在表頭中的索引位置,并記錄找到的索引。
// 查找目標(biāo)列的索引
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.目標(biāo)列數(shù)據(jù)提取與展示:
如果找到至少一個目標(biāo)列,則從工作表的第二行開始遍歷每一行,提取目標(biāo)列的數(shù)據(jù)并打印。
// 提取并打印目標(biāo)列的數(shù)據(jù)
if (!targetColumnIndices.isEmpty()) {
System.out.println("\n提取的數(shù)據(jù):");
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.資源關(guān)閉:
完成數(shù)據(jù)提取后,關(guān)閉Workbook和FileInputStream資源。
workbook.close(); file.close();
7.異常處理:
如果在處理Excel文件過程中發(fā)生IOException,捕獲異常并打印錯誤信息。
catch (IOException e) {
System.err.println("處理Excel文件時出錯: " + e.getMessage());
e.printStackTrace();
}
2.2 獲取Workbook對象
getWorkbook方法根據(jù)文件路徑的擴(kuò)展名,返回對應(yīng)的Workbook對象。如果文件擴(kuò)展名不是.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方法在給定的表頭行中查找指定列名的索引。它遍歷表頭行的每個單元格,比較單元格的字符串值(忽略大小寫)與目標(biāo)列名,若匹配則返回該單元格的索引,否則返回 -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方法根據(jù)單元格的類型,將單元格的值轉(zhuǎn)換為字符串形式返回。它支持處理字符串、數(shù)字、日期、布爾值、公式和空白等不同類型的單元格。
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();
}
}結(jié)果輸出:
請輸入Excel文件路徑: D:\pyprogect\excellianxi\all.xlsx
請輸入要提取的列名(多個列名用逗號分隔): id,age,income
找到列: id, 索引: 0
找到列: age, 索引: 1
找到列: income, 索引: 4
提取的數(shù)據(jù):
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.07
Process 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); // 獲取表頭行
// 查找目標(biāo)列的索引
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);
}
}
// 提取并打印目標(biāo)列的數(shù)據(jù)
if (!targetColumnIndices.isEmpty()) {
System.out.println("\n提取的數(shù)據(jù):");
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();
}
}
}
到此這篇關(guān)于基于Java實(shí)現(xiàn)Excel列數(shù)據(jù)提取工具的文章就介紹到這了,更多相關(guān)Java提取Excel列數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)文件下載的四種方式
本文主要介紹了SpringBoot實(shí)現(xiàn)文件下載的四種方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-11-11
解決Feign切換client到okhttp無法生效的坑(出現(xiàn)原因說明)
這篇文章主要介紹了解決Feign切換client到okhttp無法生效的坑(出現(xiàn)原因說明),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02
詳解java創(chuàng)建一個女朋友類(對象啥的new一個就是)==建造者模式,一鍵重寫
這篇文章主要介紹了java建造者模式一鍵重寫,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04
SpringBoot實(shí)現(xiàn)實(shí)時彈幕的示例代碼
實(shí)時彈幕系統(tǒng)已成為現(xiàn)代視頻網(wǎng)站和直播平臺的標(biāo)準(zhǔn)功能,它讓觀眾可以在觀看視頻時發(fā)送即時評論,本文將介紹如何使用SpringBoot構(gòu)建一個實(shí)時彈幕系統(tǒng),需要的可以了解下2025-06-06
Java WebSocket客戶端接收大量數(shù)據(jù)的三種方案
WebSocket是一種基于TCP協(xié)議的全雙工通信協(xié)議,它能夠在客戶端和服務(wù)器之間建立一個持久連接,實(shí)現(xiàn)實(shí)時的雙向數(shù)據(jù)傳輸,在實(shí)際應(yīng)用中,有時候我們需要處理大量的數(shù)據(jù),所以本文將介紹如何使用 Java WebSocket 客戶端接收大量數(shù)據(jù),并提供一些優(yōu)化方案2023-11-11
簡單了解java標(biāo)識符的作用和命名規(guī)則
這篇文章主要介紹了簡單了解java標(biāo)識符的作用和命名規(guī)則,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01

