我想读取 excel 文件(.xls、.xlsx)并将其转换为 JSON 格式并保存。
这是一个代码,它使我能够从 excel 文件中读取数据,但我无法获得如何将数据放入 JSON 格式。
谁能帮我吗。
public class ReadExcelFile {
private static XSSFWorkbook mybook;
static String fileLocation = "D://Traniee-SPG//Book1.xlsx";
public static void main(String[] args){
try{
File newFile = new File(fileLocation);
FileInputStream fIO = new FileInputStream(newFile);
mybook = new XSSFWorkbook(fIO); //finds the Excelfile
XSSFSheet mySheet = mybook.getSheetAt(0);// Return first sheet from the XLSX workbook
Iterator<Row> rowIterator = mySheet.iterator(); //create a cursor called iterator to all rows in sheet
Row r;
Cell c;
//to travel into the Excel spreadsheet
while(rowIterator.hasNext()) {
r = rowIterator.next();
//Cursor points to row
Iterator<Cell> cell_Iterator = r.cellIterator();
while(cell_Iterator.hasNext()) {
c = cell_Iterator.next();
//Cursor points to cell
switch (c.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(c.getStringCellValue()+"\t");
//System.out.println("Case String");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(c.getNumericCellValue()+"\t");
//System.out.println("Case number");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(c.getBooleanCellValue()+"\t");
System.out.println("Case boolean");
break;
case Cell.CELL_TYPE_FORMULA:
System.out.print(c.getCellFormula()+"\t");
//System.out.println("Case formula");
break;
default:
}
}
System.out.println(" ");//next to display in table format
}
mybook.close();
fIO.close();
}
catch(FileNotFoundException ef){
ef.printStackTrace();
}
catch(IOException ei){
ei.printStackTrace();
}
}
}
原文由 Prathik 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果寻找简单的在线转换工具,请使用:http: //www.convertcsv.com/csv-to-json.htm
或者像这个人一样以编程方式进行: https ://github.com/nullpunkt/excel-to-json/blob/master/src/main/java/net/nullpunkt/exceljson/convert/ExcelToJsonConverter.java