首页 > 代码库 > Java读取Excel转换成JSON字符串进而转换成Java对象

Java读取Excel转换成JSON字符串进而转换成Java对象

Jar包

技术分享

技术分享

 Excel数据

技术分享

Java代码

package ExcelToJSON;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.File;

public class Excel {
    public static void main(String[] args) {
        Sheet sheet;
        Workbook book;
        Cell cell1, cell2, cell3, cell4, cell5,cell6,cell7,cell8;
        JSONArray array = new JSONArray();
        try {
            //为要读取的excel文件名
            book = Workbook.getWorkbook(new File("F://a.xls"));

            //获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
            sheet = book.getSheet(0);

            for (int i = 1; i < sheet.getRows(); i++) {
                //获取每一行的单元格
                cell1 = sheet.getCell(0, i);//(列,行)
                cell2 = sheet.getCell(1, i);
                cell3 = sheet.getCell(2, i);
                cell4 = sheet.getCell(3, i);
                cell5 = sheet.getCell(4, i);
                cell5 = sheet.getCell(5, i);
                cell5 = sheet.getCell(6, i);
                cell5 = sheet.getCell(7, i);
                if ("".equals(cell1.getContents())) {//如果读取的数据为空
                    break;
                }
                JSONObject object = new JSONObject();
                object.put("题干",cell1.getContents());
                object.put("类型",cell2.getContents());
                object.put("A选项",cell3.getContents());
                object.put("B选项",cell4.getContents());
                object.put("C选项",cell5.getContents());
                object.put("D选项",cell5.getContents());
                object.put("答案",cell5.getContents());
                object.put("解析",cell5.getContents());
                array.add(object);
            }
            System.out.println(array.toString());
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

[{"题干":"1题题干","类型":"选择","A选项":"低电压配电柜","B选项":"自产","C选项":"低电压配电柜","D选项":"低电压配电柜","答案":"低电压配电柜","解析":"低电压配电柜"},{"题干":"2题题干","类型":"选择","A选项":"低电压配电柜","B选项":"自产","C选项":"低电压配电柜","D选项":"低电压配电柜","答案":"低电压配电柜","解析":"低电压配电柜"},{"题干":"3题题干","类型":"选择","A选项":"低电压配电柜","B选项":"外购","C选项":"低电压配电柜","D选项":"低电压配电柜","答案":"低电压配电柜","解析":"低电压配电柜"}]

 

Java读取Excel转换成JSON字符串进而转换成Java对象