我想從Java中抽取一些數據從Excel到Hashmap。爲此我使用的Apache POI庫和版本就是Java 8中的數據格式如下圖所示:從excel列中抽取字符串數據到hashmap的問題
Excel_Data.xlsx:
Title | Label A | Label B | Label C
Signal 1 | value A1 | value B1 | value C1
Signal 2 | value A2 | value B2 | value C2
Signal 3 | value A3 | value B3 | value C3
這裏寫的所有文字是String
格式,並有出現在文件中沒有數值類型
我想要什麼:
我想存儲數據的key
和value
對形式的HashMap,所以我的輸出應該是:
Expected Approach:
Key -> Value
Signal 1 -> [value A1, value B1, value C1 ...]
Signal 2 -> [value A2, value B2, value C2 ...]
Signal 3 -> [value A3, value B3, value C3 ...]
這種方法我想實現,因爲我要到另一個excel文件下列信號
Expected_output.xlsx:
Signal 1 | value A1
| value B1
| value C1
Signal 2 | value A2
| value B2
| value C2
Signal 3 | value A3
| value B3
| value C3
順序我想什麼來打印這些數據:找到這個解決方案
我試着在網上,但由於其特殊性,我沒有找到任何解決方案。我也試圖找到解決方案,key和value都是從hashmap的excel中提取的String
,但是也沒有得到太多幫助。
我想出了一個辦法,我決定來存儲Keys
到String
和Values
到ArrayList
如下圖所示代碼:
// this function loads data from excel file stored in filestream variable
public void storeData(){
//this hashmap will be used to hold values of excel file in key:values format
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
String key = null;
ArrayList<String> value = null;
try {
// get workbook instance of xlsx file
HSSFWorkbook workbook = new HSSFWorkbook(open_excel_data);
//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();
key = cell.getStringCellValue();
value.add(cell.getStringCellValue()); // I cannot think of what should be here to store labels in correct format to arraylist
if(key != null && value != null)
{
map.put(key, value);
key = null;
value = null;
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
附:
它有很多的信號的一個巨大的文件和標籤
它使用Java來完成,因爲這功能將是一個已經建立的軟件工具的一部分
你甚至可以建議我其他簡單的方法來完成這項任務,如果你有任何想法
您正在設置(在每一次循環中,在第一和)數組列表爲空,並試圖調用add()上的空。那會導致NPE。這是你面臨的問題嗎? –
另外,您不會跳過第一行,這似乎並不是您製作的地圖所必需的。 –
另外,您正在設置每個單元格的值。 –