如果你對里面的代碼不熟悉不知道的話,建議先瀏覽一遍代碼再拿去用糠悯,
這里我介紹一下這個過程的思路:
1、定義變量那些就不說了 盏道,
2稍浆、首先是上傳文件并保存的代碼
3、根據(jù)excel表的路徑來讀取文件猜嘱,之后便是先獲取最大行數(shù)和最大列數(shù)衅枫,然后根據(jù)最大行數(shù)和最大列數(shù)來循環(huán)表格。循環(huán)行的過程中循環(huán)列朗伶,獲取到一行中所有的列數(shù)據(jù)再對數(shù)據(jù)進行處理弦撩,根據(jù)需求給每一個列的數(shù)據(jù)分配一個名字,也是k-y论皆,然后再進行存儲益楼。
!点晴!反正代碼下面感凤,不懂可以私信,或者自己打斷點調(diào)試粒督,看兩遍就會理解里面的內(nèi)容了
@RequestMapping(value = "/ImportExcel")
@ResponseBody
public JSONObject ImportExcel(@RequestParam(value = "file", required = false) MultipartFile file) throws Exception {
//這里創(chuàng)建json對象陪竿,實測用map的話,json數(shù)據(jù)會有問題
JSONObject jsonMap = new JSONObject();
Sheet sheet = null; //excel的表
Row row = null; //行
String cellData = null; //列數(shù)據(jù)
//以上是定義一些要用的變量==========================================================
//講選擇的文件上傳到upload目錄
String fileName = file.getOriginalFilename();
// 獲取上傳目錄的路徑
String path = request.getRealPath("/upload");// 獲取上傳文件路徑
String prefix = fileName.substring(fileName
.lastIndexOf('.') + 1);// 獲取文件后綴名
Date time = new Date();
String filename = time.getYear() + "" + time.getMonth() + ""
+ time.getDay() + "" + time.getHours() + "" + time.getMinutes()
+ "" + time.getSeconds() + "";
File targetFile = new File(path, filename + "."
+ prefix);
//保存文件
file.transferTo(targetFile);
//以上先上傳并把文件保存到服務(wù)器==========================================================
// 獲取上傳目錄的路徑
Workbook wb =EXCELBean.readExcel(path+"\\"+filename + "." + prefix);
if(wb != null){
//用來存放表中一行的數(shù)據(jù)
List<JSONObject> listMap = new ArrayList<JSONObject>();
//獲取第一個sheet
sheet = wb.getSheetAt(0);
//獲取最大行數(shù)
int rownum = sheet.getPhysicalNumberOfRows();
//獲取第一行
row = sheet.getRow(0);
//獲取最大列數(shù)
int colnum = row.getPhysicalNumberOfCells();
//循環(huán)行
for (int i = 1; i < rownum; i++) {
row = sheet.getRow(i);
if(row !=null){
//創(chuàng)建list對象接收讀出的excel一行中列的數(shù)據(jù)
List<String> list = new ArrayList<String>();
//循環(huán)列
for (int j=0;j<colnum;j++){
cellData = (String) EXCELBean.getCellFormatValue(row.getCell(j));
list.add(cellData);
}
//這里可以定義多個JSONObject來對數(shù)據(jù)進行處理嵌套等操作屠橄,最后再儲存到listMap中族跛,
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("skvDorCode0",list.get(0));
jsonObject2.put("skvDorCode1",list.get(1));
jsonObject2.put("skvDorCode2",list.get(2));
jsonObject2.put("skvDorCode3",list.get(3));
jsonObject2.put("skvDorCode4",list.get(4));
jsonObject2.put("skvDorCode5",list.get(5));
/*//創(chuàng)建jsonBmt對象,進一步把以上對象嵌套
JSONObject jsonBmt = new JSONObject();
//把以上幾個嵌套入第一層對象中
jsonObject2.put("businessMixTypes",jsonBmt); */
listMap.add(jsonObject2);
}else{
break;
}
}// end for row
//最外層加個key-gridData
jsonMap.put("msg", "上傳數(shù)據(jù)成功");
jsonMap.put("gridData", listMap);
System.out.println(jsonMap);
return jsonMap;
}
jsonMap.put("msg", "上傳數(shù)據(jù)為空");
return jsonMap;
}