java 读取excel内容转为JSONArray
需要引入的JAR
1 <!--*.xls--> 2 <dependency> 3 <groupId>net.sourceforge.jexcelapi</groupId> 4 <artifactId>jxl</artifactId> 5 <version>2.6.8</version> 6 </dependency> 7 <dependency> 8 <groupId>com.alibaba</groupId> 9 <artifactId>fastjson</artifactId> 10 <version>1.2.7</version> 11 </dependency>
测试类
1 import com.alibaba.fastjson.JSONArray; 2 import com.alibaba.fastjson.JSONObject; 3 import jxl.Cell; 4 import jxl.Sheet; 5 import jxl.Workbook; 6 7 import java.io.File; 8 9 public class ExcelOperate { 10 11 public static void main(String[] args) { 12 Sheet sheet; 13 Workbook book; 14 Cell cell1, cell2, cell3, cell4, cell5; 15 JSONArray array = new JSONArray(); 16 try { 17 //为要读取的excel文件名 18 book = Workbook.getWorkbook(new File("D://b.xls")); 19 20 //获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....) 21 sheet = book.getSheet(0); 22 23 for (int i = 1; i < sheet.getRows(); i++) { 24 //获取每一行的单元格 25 cell1 = sheet.getCell(0, i);//(列,行) 26 cell2 = sheet.getCell(1, i); 27 cell3 = sheet.getCell(2, i); 28 cell4 = sheet.getCell(3, i); 29 cell5 = sheet.getCell(4, i); 30 if ("".equals(cell1.getContents())) {//如果读取的数据为空 31 break; 32 } 33 JSONObject object = new JSONObject(); 34 object.put("ID",cell1.getContents()); 35 object.put("编号",cell2.getContents()); 36 object.put("姓名",cell3.getContents()); 37 object.put("数量",cell4.getContents()); 38 object.put("住址",cell5.getContents()); 39 array.add(object); 40 } 41 System.out.println(array.toString()); 42 book.close(); 43 } catch (Exception e) { 44 e.printStackTrace(); 45 } 46 } 47 }
![](https://images2018.cnblogs.com/blog/648026/201804/648026-20180423182022228-1759156908.jpg)