java代码:
public void importFile() throws Exception{
UserContext userContext = (UserContext)getSessionContent("userContext");
HttpServletRequest request = getRequest();
//上传文件
MultiPartRequestWrapper mpRequest = (MultiPartRequestWrapper)ServletActionContext.getRequest();
File[] files = mpRequest.getFiles("excelPath");
String[] fileNames = mpRequest.getFileNames("excelPath");//"upload"是页面中上传文件file的name的值;
System.out.println(fileNames);
String realPath = request.getSession(true).getServletContext().getRealPath("/");
String sp = System.getProperty("file.separator");
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHH");
String name = "";
if(fileNames!=null){
for(int i=0;i<fileNames.length;i++){
name = realPath+"temp"+sp+format.format(new Date())+fileNames[i];
File targetFile = new File(realPath+"temp"+sp+format.format(new Date())+fileNames[i]);
FileUtils.copyFile(files[i], targetFile);
}
}
//导入数据
String filePath = name;
try {
String returnValue =thirdBudgetAdjService.importExcel(filePath,userContext);
if(returnValue.equals("SUCCESS")){
back2Page("thirdBudgetAdjAction", "showAdjList", false, "导入成功");
}
if(returnValue.equals("NOBudget")){
back2Page("thirdBudgetAdjAction", "showImport", false, "导入失败,文件中有系统不存在预算科目,请重新选择文件!");
}
} catch (Exception e) {
e.printStackTrace();
setIsProcFinish( "success" );
back2Page("thirdBudgetAdjAction", "showImport", false, "导入失败");
}
}
html代码:
<div align="center">
<h1>导入Excel</h1>
<hr>
<form method="post" enctype="multipart/form-data" id="empForm">
<input type="file" id="excelPath" name="excelPath"/>
<input type="button" value="导入Excel" οnclick="importEmp()"/>
</form>
</div>
js:
<script type="text/javascript">
//Excel文件导入到数据库中
function importEmp(){
//检验导入的文件是否为Excel文件
var excelPath = document.getElementById("excelPath").value;
if(excelPath == null || excelPath == ''){
alert("请选择要上传的Excel文件");
return;
}else{
var fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();
if(fileExtend == '.xls' ){
}else{
alert("文件格式需为'.xls'格式");
return;
}
}
//提交表单
document.getElementById("empForm").action="<%=path %>/filter/budgetContractAction_importFile.action? excelPath="+excelPath;
//document.getElementById("empForm").action="<%=path %>/filter/budgetContractAction_uploadFile.action? excelPath="+excelPath;
document.getElementById("empForm").submit();
}
</script>