下面是我的代码,我试图使用Apache POI读取excel数据,并希望通过将First列值作为键,将最后一列作为值来存储Hashmap中的第一列和最后一列值。将值放在hashmap中时,我遇到了一个问题。我的预期输出应该是
Key value
UserDefined Xpath_original
seldriver xpath;//div[@id='mBody']
Selenium xpath;//table[@id='choice']/tbody/tr/td[1]/ul/li[1]
但我得到的输出为
*
null null
null
null xpath;//div[@id='mBody']
* 下面是我的一段代码
package com.selenium.common;
import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadMacroExcel {
public static void main(String[] args) {
try {
File f=new File("C:\\Users\\Rajaram.8.Kannuri\\Downloads\\Fire-IEBrowser1.4.xlsm");
HashMap <String,String> innerMap =null;
Workbook workbook = WorkbookFactory.create(f);
System.out.println(workbook);
int numberOfSheets = workbook.getNumberOfSheets();
org.apache.poi.ss.usermodel.Sheet sheet=null;
String key = "";
String value = "";
//Get the sheet in the xlsx file
for (int i = 0; i < numberOfSheets; i++) {
sheet = workbook.getSheetAt(i);
System.out.println(sheet.getSheetName());
int firstColumn = sheet.getRow(0).getFirstCellNum();
int lastColumn = sheet.getRow(0).getLastCellNum();
Iterator<Row> rowIterator = sheet.iterator();
innerMap = new HashMap<String,String>();
while(rowIterator.hasNext())
{
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
if(cell.getColumnIndex()==firstColumn||cell.getColumnIndex()==lastColumn-1)
{
switch (cell.getCellType())
{
case Cell.CELL_TYPE_STRING:
key = cell.getStringCellValue();
/*System.out.print(key + "\t");*/
/* Thread.sleep(5000);*/
break;
case Cell.CELL_TYPE_FORMULA:
value = cell.getRichStringCellValue().toString();
/*System.out.print(value + "\t");*/
/*Thread.sleep(5000);*/
break;
}
System.out.print(innerMap.put(key,value));
}
}
System.out.println("");
}
/* System.out.println(innerMap.get("UserDefined"));*/
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
任何人都可以帮我解决这个问题吗?
答案 0 :(得分:3)
您似乎正在尝试使用
打印插入的值System.out.print(innerMap.put(key,value));
但是,put
会返回与给定密钥关联的上一个值,如果没有该密钥的映射,则返回null
。
另见https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-
您应该使用类似
的内容innerMap.put(key,value); // add the new mapping to the hashmap
System.out.print(innerMap); // dumps the complete map with all entries
System.out.print(innerMap.get(key)); // dumps the value for the recently inserted key