前端页面
<form enctype="multipart/form-data" id="uploadForm"
target="id_iframe">
<label class="col-md-1 label-control" style="text-align: right;">表格导入:</label>
<div class="col-md-11">
<input id="f_upload" name="f_upload" type="file" multiple="multiple" />
</div>
<div class="col-md-1" style="margin-top: 15px;">
<input class="btn btn-green btn-sm" type="submit" id="submit"
style="width: 100px" value="提交">
</div>
</form>
###JS代码
$("#submit").click(
function(e){
var file = $("#f_upload").val();
if (file == null || file == "" || file == undefined) {
layer.msg('请选择文件!', {time: 2000,icon: 2,});
return false;
} else {
var data =new AjaxForm('#uploadForm', compileUrl('${rc.contextPath}/dict/uploadDiagnosis'), {}).execute();
parent.layer.msg("导入成功", {icon: 1});
parent.refreshTable();
btnClose();
}
}
)
###后台工具类
public static Map<Integer, Map<Integer,Object>> readExcelContentz(MultipartFile file) throws Exception{
Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();
// 上传文件名
Workbook wb = getWb(file);
if (wb == null) {
throw new Exception("Workbook对象为空!");
}
Sheet sheet = wb.getSheetAt(0);
// 得到总行数
int rowNum = sheet.getLastRowNum();
Row row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文内容应该从第二行开始,第一行为表头的标题
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
Object obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
//根据Cell类型设置数据
private static Object getCellFormatValue(Cell cell) {
Object cellvalue = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
case Cell.CELL_TYPE_FORMULA: {
if (DateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
cellvalue = date;
} else {
cellvalue = (int)cell.getNumericCellValue();
}
break;
}
case Cell.CELL_TYPE_STRING:
cellvalue = cell.getRichStringCellValue().getString();
break;
default:
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
private static Workbook getWb(MultipartFile mf){
String filepath = mf.getOriginalFilename();
String ext = filepath.substring(filepath.lastIndexOf("."));
Workbook wb = null;
try {
InputStream is = mf.getInputStream();
if(".xls".equals(ext)){
wb = new HSSFWorkbook(is);
}else if(".xlsx".equals(ext)){
wb = new XSSFWorkbook(is);
}else{
wb=null;
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
return wb;
}
###Controller部分
@PostMapping("/uploadDiagnosis")
@ResponseBody
public Map<String,Object> uploadDiagnosis(@RequestParam("f_upload") MultipartFile file, String doc_type) throws AppException {
return dictService.uploadDiagnosis(file);
}