gpt4 book ai didi

java - 如何将Excel中的值分组到HashMap

转载 作者:行者123 更新时间:2023-12-02 07:02:40 25 4
gpt4 key购买 nike

我有以下Excel:

Method Name       Status Code
getLoggedinUserDetails 400
createRequisition 400
excelMDM 400

我可以使用以下代码打印 Excel 中的值:

package com.poc.excelfun;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;

import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;

public class ReadExcelData {
public static void main(String[] args) {
try {

FileInputStream file = new FileInputStream(new File("attachment_status.xls"));

//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);

//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);

//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();

//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {

Cell cell = cellIterator.next();

switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print((int)cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

我想将不包括标题Method Name Status Code的值和仅像Key -> getLoggedinUserDetails和value -> 400这样的值放入Hashmap

如何做到这一点。

请帮我找到这个。

最佳答案

试试这个代码:

Iterator<Cell> cellIterator = row.cellIterator();

String key = null
int value = Integer.MIN_VALUE; // use a default value that will never occur in the sheet

HashMap<String, Integer> map = new HashMap<String, Integer>();

while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();

switch(cell.getCellType())
{
case Cell.CELL_TYPE_NUMERIC:
value = cell.getNumericCellValue(); break;
case Cell.CELL_TYPE_STRING:
key = cell.getStringCellValue(); break;
}

if(key != null && value != Integer.MIN_VALUE)
{
map.put(key, value);
key = null;
value = Integer.MIN_VALUE;
}
}

不是最干净的解决方案,但应该与适合您的数据格式的迭代器一起使用。

如果您的电子表格框架允许通过索引查找特定单元格,您可以通过替换 while 循环来使其更容易,并且可以直接从单元格中检索值。

关于java - 如何将Excel中的值分组到HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16458640/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com