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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM