1.前台请求
var formData = new FormData();
formData.append("file",$("#file_Excel")[0].files[0]);
$.ajax({
url : sy.contextPath+'/base/management-account!doNotNeedSecurity_readExcel.sy',
type : 'POST',
dataType: 'json',
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
//console.log("正在进行,请稍候");
},
success : function(data) {
parent.$.messager.progress('close');
//alert(data.success);
if(data.success){
parent.$("#mainInfo").datagrid('reload');
parent.dialog.dialog("close");
}else{
$.messager.alert('提示', '导入失败!'+data.msg, 'error');
}
},
error : function(data) {
console.log(data.msg);
}
});
2.后台接收
private File file; // jsp页面传来的文件
private String fileFileName; // jsp页面传来的文件的文件名
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
boolean isE2007 = false; // 判断是否是excel2007格式
if (fileFileName.endsWith("xlsx")) {
isE2007 = true;
}
InputStream input = null;
try {
input = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} // 建立输入流
Workbook wb = null;
try {
if (isE2007) {
wb = new XSSFWorkbook(input);
} else {
wb = new HSSFWorkbook(input);
}
} catch (IOException e) {
e.printStackTrace();
}
// 根据文件类型调用不同的poi方法
int se = wb.getNumberOfSheets();
Sheet sheet = wb.getSheetAt(0);// 得到sheet
// int fisrt = sheet.getFirstRowNum();//获取第一行
/*Row sheetHead = sheet.getRow(sheet.getFirstRowNum());// 表头
for (int count = 0; count < sheetHead.getLastCellNum(); count++) {
Cell cell = sheetHead.getCell(count);
String cellValue = "";
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue().replace("\t", "").trim();
}
headList.add(cellValue);
}*/
int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();//获得总列数
int rowNum=sheet.getLastRowNum();//获得总行数
List<HashMap> list = new ArrayList<HashMap>();
for(int i=2;i<=rowNum;i++){
Row row = sheet.getRow(i);
HashMap map = new HashMap();
map.put("NSRSBH", row.getCell(0));
map.put("ZFMC", row.getCell(1));
map.put("ZFTZZB", row.getCell(2));
map.put("WGTZFMC", row.getCell(3));
map.put("WFTZZB", row.getCell(4));
map.put("JWQYMC", row.getCell(5));
map.put("XMSZG", row.getCell(6));
map.put("SLFS", row.getCell(7));
map.put("ZCZB", row.getCell(8));
map.put("JYFW", row.getCell(9));
map.put("HTZE", row.getCell(10));
map.put("WFTZZE", row.getCell(11));
list.add(map);
}