我将读取一个excel
文件并将其转换为json
并创建json
文件。
代码: (我已经尝试过)
public static void main(String[] args) throws IOException, InvalidFormatException {
// Creating a Workbook from an Excel file (.xls or .xlsx)
Workbook workbook = WorkbookFactory.create(new File(
"C:\\Users\\SomeExcel.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
// Create a DataFormatter to format and get each cell's value as String
DataFormatter dataFormatter = new DataFormatter();
System.out.println("\n\nIterating over Rows and Columns using for-each loop\n");
for (Row row : sheet) {
for (Cell cell : row) {
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
System.out.println();
}
// Closing the workbook
workbook.close();
}
我有点坚持将单元格内容转换为json键值对。
请检查并告知我。
答案 0 :(得分:0)
您可以使用Apache POI阅读excel并使用JsonGenerator生成Json:
JsonFactory factory = new JsonFactory();
JsonGenerator generator = factory.createGenerator(
new File("data/output.json"), JsonEncoding.UTF8);
generator.writeStartObject();
generator.writeStringField("stringField", "stringValue");
generator.writeNumberField("numericField", 25);
generator.writeEndObject();
generator.close();
答案 1 :(得分:0)
从这个问题尚不清楚您在哪里停留,我假设您已经从excel部分中弄清了读数,在读取时,您只需要将单元格的值插入到Map中,然后将其转储到json,我如下使用Jackson lib
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
// this should happen in a for loop (reading from the excel file)
map.put("ABCD", "hello");
map.put("key1", "value1");
try {
String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
答案 2 :(得分:0)
感谢其他答案,我尝试并提供了该信息并找到了解决方案。
代码:
FileInputStream file = new FileInputStream(new File("C:\\Users\\SomeExcel.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
SomePojo somePojo = new SomePojo();
Map<Object, Object> x = new LinkedHashMap<>();
// ignoring header for that I've +1 in loop
for(int i = sheet.getFirstRowNum() + 1; i<=sheet.getLastRowNum(); i++)
{
Row row = sheet.getRow(i);
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
Cell ce = row.getCell(j);
if (j == 0) {
// If you have Header in text It'll throw exception because it won't get
// NumericValue
somePojo.setName(ce.getStringCellValue());
}
if (j == 1) {
somePojo.setValue(ce.getStringCellValue());
}
// Same for third column
}
x.put(somePojo.getName(), somePojo.getValue());
}
// Object to JSON in String
ObjectMapper mapper = new ObjectMapper();
// Object to JSON in file
mapper.writeValue(new File("C:\\some.json"),x);
// Print in console
String jsonFromMap = mapper.writeValueAsString(x);
file.close();
SomePojo.java
public String name;
public String value;