将Excel中的数据转换成JSON格式
第一步:下载jxl.jar包
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
第二步:代码编写(注意:jxl依赖包只能获取文件名后缀为“.xls"的文件)
@GET
@Path("/changeExcel")
public Response changeExcel(){
Sheet sheet;
Workbook book;
Cell cell1, cell2, cell3, cell4, cell5,cell6,cell7,cell8;
JSONArray array = new JSONArray();
try {
//为要读取的excel文件名
book = Workbook.getWorkbook(new File("D:\\Rule\\rule.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);
cell6 = sheet.getCell(5, i);
cell7 = sheet.getCell(6, i);
cell8 = sheet.getCell(7, i);
/*if ("".equals(cell1.getContents())) {//如果读取的数据为空
break;
}*/
JSONObject object = new JSONObject();
object.put("Category",cell1.getContents());
object.put("No",cell2.getContents());
object.put("DomainOld",cell3.getContents());
object.put("DomainNew",cell4.getContents());
object.put("DomainChangeType",cell5.getContents());
object.put("ComponentOld",cell6.getContents());
object.put("ComponentNew",cell7.getContents());
object.put("ComponentChangeType",cell7.getContents());
array.put(object);
//array.add(object);
}
System.out.println(array.toString());
book.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(array.toString());
return Response.ok(array.toString()).build();
}
|