1
我正在閱讀xlsx文件使用Apache POI
。我能夠取得結果,並且實體計數成功。但我想在JSON中獲得我的結果,以便我可以使用此JSON數據製作google graph
或任何graph API
。我是java新手,我該怎麼做?任何幫助將不勝感激。我怎樣才能讓我的javacode輸出爲json
我的代碼詳情如下。
package com.amiku.Excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
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.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelReader
{
public static void main(String[] args) throws IOException{
{
FileInputStream fis = new FileInputStream(new File("C:\\Users\\amiku\\eclipse-workspace\\Amiku\\cloudstreams-connectors-downloads.xlsx"));
//create workInstance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
//create a sheet object to retrive the sheet
XSSFSheet sheet = wb.getSheetAt(0);
//that is for evalute the cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
Map<String, Integer> Details = new HashMap<String,Integer>();
int i=0;
List<String> l = new ArrayList<String>();
for (Row row : sheet)
{
for (Cell cell : row) {
l.add(cell.getStringCellValue());
/*HashMap map = new HashMap();
map.put(cell.getStringCellValue());*/
}
/*switch(formulaEvaluator.evaluateInCell(cell).getCellType())
{*/
/*//if cell has a numeric format
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
// if cell has a string format
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}*/
i++;
System.out.println();
}
for (int j = 0; j < l.size(); j++) {
if (j % 2 == 1) {
String var = l.get(j);
if (Details.containsKey(var)) {
Details.put(var, Details.get(var) + 1);
} else {
Details.put(var, 1);
}
}
}
Iterator it = Details.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry) it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}
}
}
我的結果此代碼的圖片在這裏。
嘗試使用Gson庫https://github.com/google/gson –
有幾個庫可以幫助你解決這個問題。 一個是谷歌GSON(https://github.com/google/gson)(我喜歡),另一個我用過的是傑克遜(https://github.com/FasterXML/jackson)Jackson遵守嚴格的JSON結構定義比GSON更好,儘管GSON在我的opion中更易於使用。我希望這會有所幫助,乾杯,布拉姆 –