Java Excel匯入及資料解析詳解
阿新 • • 發佈:2019-02-08
批量更新:<select class="default_input" id="plgx_id"> <option value="s0">批量更新</option> <option value="s1">狀態</option> <option value="s2">借讀</option> <option value="s3">性別</option> <option value="s4">學號</option> <option value="s5">繳費資訊</option> <option value="s6">班級</option> </select>
<!--彈出視窗1 批量更新--> <div class="popup_background" id="plgx_1"> <div class="center_popup"> <h3>批量更新狀態</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input id="input-file-1" type="file" name="file" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdateState()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div> <div class="popup_background" id="plgx_2"> <div class="center_popup"> <h3>批量更新借讀</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input type="file" id="input-file-2" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdateReade()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div> <div class="popup_background" id="plgx_3"> <div class="center_popup"> <h3>批量更新性別</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input type="file" id="input-file-3" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdateGender()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div> <div class="popup_background" id="plgx_4"> <div class="center_popup"> <h3>批量更新學號</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input type="file" id="input-file-4" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdateStuNO()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div> <div class="popup_background" id="plgx_5"> <div class="center_popup"> <h3>批量更新繳費資訊</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input type="file" id="input-file-5" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdatePayment()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div> <div class="popup_background" id="plgx_6"> <div class="center_popup"> <h3>批量更新班級</h3> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form_div"> <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12"> <input type="file" id="input-file-6" class="dropify-fr" data-default-file="" /> </div> <div class="center_button_div"> <button class="default_btn edit_row_btn" onclick="batchUpdateClazz()">確定</button> <button class="default_btn anti_btn clicked close_btn" onclick="close_window()">取消</button> </div> </div> </div> </div>
//點選彈出視窗2 $("#plgx_id").on("change", function() { var n = $(this).val(); console.log(n); switch (n) { case 's1': popup_name = $("#plgx_1"); open_window(); break; case 's2': popup_name = $("#plgx_2"); open_window(); break; case 's3': popup_name = $("#plgx_3"); open_window(); break; case 's4': popup_name = $("#plgx_4"); open_window(); break; case 's5': popup_name = $("#plgx_5"); open_window(); break; case 's6': popup_name = $("#plgx_6"); open_window(); break; } $(this).val("s0"); });
function batchUpdateState() {
var formData = new FormData();
var name = $("#input-file-1").val();
formData.append("file", $("#input-file-1")[0].files[0]);
formData.append("name", name);
$.ajax({
url : '../biz/sch/student/batchImportStudents',
type : 'POST',
cache : false,
data : formData,
// 告訴jQuery不要去處理髮送的資料
processData : false,
// 告訴jQuery不要去設定Content-Type請求頭
contentType : false,
beforeSend : function() {
console.log("正在進行,請稍候");
},
success : function(responseStr) {
alert("匯入成功");
}
});
close_window();
$(".dropify-clear").trigger("click");
}
@ResponseBody
@PostMapping("/batchImportStudents")
public JSONObject batchImportStudents(@RequestParam("file") MultipartFile file,HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
System.out.println("================================");
JSONObject jo = null;
JSONObject param = new JSONObject();
param.put("schId", 280010);
param.put("sheetName", "測試");
//獲取學校
try {
String originalFilename = file.getOriginalFilename();//原檔名字
param.put("fileName", originalFilename);
InputStream is = file.getInputStream();//獲取輸入流
ReadExcel readExcel = new ReadExcelImpl();
//ExcelCheckCallback<JSONObject> callback = new StuPLXHCheckCallback();
ExcelCheckCallback<JSONObject> callback = null;
List<JSONObject> list = readExcel.readExcel(is, callback, param );
if(list != null && !list.isEmpty())
jo = list.get(0);
System.out.println("jo: "+jo.toJSONString());
} catch (FileUploadException e) {
e.printStackTrace();
response.setStatus( 500);
return null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jo;
}
package com.moofen.core.util.excel;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import com.alibaba.fastjson.JSONObject;
public interface ReadExcel {
@SuppressWarnings("rawtypes")
List<JSONObject> readExcel(InputStream is, ExcelCheckCallback callback, JSONObject param ) throws Exception, IOException, FileUploadException;
}
package com.moofen.core.util.excel.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.fileupload.FileUploadException;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.constant.ExcelConstant;
import com.moofen.core.util.excel.AbstractRead;
import com.moofen.core.util.excel.ExcelCheckCallback;
import com.moofen.core.util.excel.ReadExcel;
public class ReadExcelImpl implements ReadExcel {
@SuppressWarnings("rawtypes")
@Override
public List<JSONObject> readExcel(InputStream is,
ExcelCheckCallback callback, JSONObject param)
throws Exception, IOException, FileUploadException {
//List<FileItem> fileItems = readFileItemFromHttp(request);
//JSONObject p = buildParam( readAllParam(fileItems), param);
AbstractRead reader = null;
List<JSONObject> list = new ArrayList<JSONObject>();
String fName = param.getString("fileName");
String fileName[] = fName.split("\\.");
String suffix = fileName[fileName.length - 1].toLowerCase();
if(suffix.endsWith(ExcelConstant.FILE_UPLOAD_LIMIT_XLS)){
reader = new ReadXls();
}else if(suffix.endsWith(ExcelConstant.FILE_UPLOAD_LIMIT_XLSX)){
reader = new ReadXlsx();
}
JSONObject jo = reader.readExcel(is, null, null);
list.add(jo);
return list;
}
}
package com.moofen.core.util.excel.impl;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.util.excel.AbstractRead;
import com.moofen.core.util.excel.ExcelCheckCallback;
public class ReadXls extends AbstractRead{
HSSFWorkbook hssfWorkbook = null;
@SuppressWarnings({ "rawtypes", "unchecked" })
public JSONObject readExcel(InputStream is, JSONObject param, ExcelCheckCallback callback) throws Exception, IOException{
hssfWorkbook = new HSSFWorkbook(is);
try{
JSONObject ret = new JSONObject();
Integer ss = 0, es = hssfWorkbook.getNumberOfSheets();
// Read the Sheet
for (int numSheet = ss; numSheet < es; numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
JSONArray sheetAry = new JSONArray();
// Read the Row
if(hssfSheet.getRow(0) == null){
//logger.info(hssfSheet.getSheetName()+" 無內容");
continue;
}
int coloumNum=hssfSheet.getRow(0).getPhysicalNumberOfCells();
for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
List<String> rowData = new ArrayList<String>();
for( int c = 0; c < coloumNum; c++){
HSSFCell cellV = hssfRow.getCell( c );
if(cellV != null)
rowData.add( getValue(cellV) );
else
rowData.add("");
}
sheetAry.add( rowData);
}
}
ret.put(hssfSheet.getSheetName(), sheetAry);
}
// ret = callback.beforeHandleData(ret, param);
// if(callback.check(ret, param) == false){
// throw new Exception( callback.getCheckInfo() );
// }
// ret = callback.afterHandleData(ret, param);
return ret;
}catch(Exception e){
throw e;
}finally{
is.close();
}
}
}
package com.moofen.core.util.excel.impl;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.moofen.core.util.excel.AbstractRead;
import com.moofen.core.util.excel.ExcelCheckCallback;
public class ReadXlsx extends AbstractRead{
XSSFWorkbook xssfWorkbook = null;
@SuppressWarnings({ "unchecked", "rawtypes" })
public JSONObject readExcel(InputStream is, JSONObject param, ExcelCheckCallback callback)
throws Exception, IOException {
try{
xssfWorkbook = new XSSFWorkbook(is);
JSONObject ret = new JSONObject();
Integer ss = 0, es = xssfWorkbook.getNumberOfSheets();
// Read the Sheet
for (int numSheet = ss; numSheet < es; numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
return null;
}
JSONArray list = new JSONArray();
// Read the Row
if(xssfSheet.getRow(0) == null){
//logger.info(xssfSheet.getSheetName()+" 無內容");
continue;
}
int coloumNum=xssfSheet.getRow(0).getPhysicalNumberOfCells();
for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
JSONArray line = new JSONArray();
for( int c = 0; c < coloumNum; c++){
XSSFCell cellV = xssfRow.getCell( c );
if(cellV != null)
line.add(getValue(cellV));
else
line.add("");
}
list.add( line);
}
}
ret.put(xssfSheet.getSheetName(), list);
}
// ret = callback.beforeHandleData(ret, param);
// if(callback.check(ret, param) == false){
// throw new Exception( callback.getCheckInfo() );
// }
// ret = callback.afterHandleData(ret, param);
return ret;
}catch(Exception e){
throw e;
}finally{
is.close();
}
}
}
package com.moofen.core.util.excel;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.NumberToTextConverter;
import com.alibaba.fastjson.JSONObject;
public abstract class AbstractRead {
@SuppressWarnings("rawtypes")
public abstract JSONObject readExcel(InputStream is, JSONObject param, ExcelCheckCallback callback) throws Exception, IOException;
protected String getValue(Cell c) {
String r=null;
if(c==null){
r="";
}
switch(c.getCellType()){
case Cell.CELL_TYPE_BLANK://為 空值3
r="";
break;
case Cell.CELL_TYPE_BOOLEAN://boolean型4
r=c.getBooleanCellValue()+"";
break;
case Cell.CELL_TYPE_ERROR://錯誤 5
r="";
break;
case Cell.CELL_TYPE_FORMULA://公式型 2
Workbook wb = c.getSheet().getWorkbook();//取得workbook
CreationHelper helper = wb.getCreationHelper();//取得wb的幫助
FormulaEvaluator ev = helper.createFormulaEvaluator();//取得helper的公式計算方法
r=getValue(ev.evaluateInCell(c));//呼叫自身方法,括號裡取得cellValue
break;
case Cell.CELL_TYPE_NUMERIC://數值型 0
if(DateUtil.isCellDateFormatted(c)){//如果是excel日期格式
SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//規定日期格式
Date d = c.getDateCellValue();//取得日期
r = s.format(d);//轉換日期格式
}else{
// r = getNumber( String.valueOf(c.getNumericCellValue()) );//數值的話,轉換為String
r = NumberToTextConverter.toText(c.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING://字串型 1
r=c.getRichStringCellValue().toString();//推薦使用getRichStringCellValue();
//getStringCellValue()為老方法
break;
default:
r="";
}
return r.trim();
}
/* private String getNumber( String num ){
String[] tmp = num.split("\\.");
if(tmp.length == 2){
Integer i = Integer.parseInt( tmp[1] );
if(i > 0)
return num;
else
return tmp[0];
}else{
return num;
}
}*/
}