【java】提取excel轉json
阿新 • • 發佈:2017-10-23
print code .cn object exceptio ace json keyset read
1 import jxl.Cell; 2 import jxl.Sheet; 3 import jxl.Workbook; 4 import net.sf.json.JSONArray; 5 import net.sf.json.JSONObject; 6 7 import java.io.FileInputStream; 8 import java.io.InputStream; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 public class Main { 13 14 publicstatic void main(String[] args) { 15 String excelPath = "E:\\workspace\\HelloWorld\\data\\fund.xls"; 16 Map<String,String> fundMaps = readExcel(excelPath); 17 jsonBuild(fundMaps); 18 } 19 20 private static void jsonBuild(Map fundMaps) { 21 int size = fundMaps.size();22 for(Object key : fundMaps.keySet()) { 23 Object displayName = fundMaps.get(key); 24 JSONObject jsonObject = new JSONObject(); 25 JSONArray jsonArray = new JSONArray(); 26 JSONObject jsonInnerObject1 = new JSONObject(); 27 JSONObject jsonInnerObject2 = newJSONObject(); 28 jsonInnerObject1.put("keywordsInput", displayName); 29 jsonInnerObject1.put("weight", "10"); 30 jsonInnerObject2.put("keywordsInput", key); 31 jsonInnerObject2.put("weight", "12"); 32 jsonArray.add(jsonInnerObject1); 33 jsonArray.add(jsonInnerObject2); 34 jsonObject.put("keywordsType", "product"); 35 jsonObject.put("keywordsDisplay", displayName+" "+key); 36 jsonObject.put("array", jsonArray); 37 System.out.println(jsonObject+","); 38 } 39 } 40 41 private static Map<String,String> readExcel(String excelPath) { 42 Workbook excelRead; 43 Map fundMaps = new HashMap<String, String>(); 44 try { 45 InputStream instream = new FileInputStream(excelPath); 46 excelRead = Workbook.getWorkbook(instream); 47 Sheet sheetRead = excelRead.getSheet(0); 48 int rows = sheetRead.getRows(); 49 for (int i = 1; i < rows; i++) { 50 Cell cell0 = sheetRead.getCell(0, i); 51 Cell cell1 = sheetRead.getCell(1, i); 52 fundMaps.put(cell0.getContents(), cell1.getContents()); 53 } 54 } catch (Exception e) { 55 System.out.println("excel read failed : " + e); 56 } 57 return fundMaps; 58 } 59 }
附1:json格式
1 { 2 keywordsType:"product", 3 keywordsDisplay:"基金2 2", 4 array:{ 5 { 6 keywordsInput:"基金2", 7 weight:"10" 8 }, 9 { 10 keywordsInput:"2", 11 weight:"12" 12 } 13 } 14 }
附2:jar包下載
【1】json jar包下載 :
http://www.sojson.com/blog/20.html
http://www.cnblogs.com/xihuanyuye/p/5984679.html
【2】excel jar包下載:
http://www.cnblogs.com/wuxinrui/archive/2011/03/20/1989326.html
【java】提取excel轉json