Struts.xml部分
<package name="com.crm.workbench.activity" namespace="/activity" extends="struts-default,json-default">
<action name="uploadMarkActive" class="com.crm.workbench.activity.action.MarketActiveController" method="uploadMarkActive">
<result type="json">
<param name="root">map</param>
</result>
</action>
</package>
Action部分
private File excel; //上传的文件
private String excelFileName; //上传文件的名称 固定写法:上传的文件+FileName
excel和excelFileName的set、get方法
public String uploadMarkActive(){
//先定义一个临时文件夹,存放用户上传的Excel文件
String tempDir = "/upload/Excel";
//获取临时文件夹的全路径
String tempDirRealPath = ServletActionContext.getServletContext().getRealPath(tempDir);
//获取当前用户的信息
UserVo user = (UserVo)ServletActionContext.getRequest().getSession().getAttribute("user");
//创建上传文件对象
File target = new File(tempDirRealPath,excelFileName);
//删除之前上传的旧文件
if(target.exists()){
target.delete();
}
try {
//将文件复制到临时文件夹中
FileUtils.copyFile(excel,target);
//解析文件,将Excel文件中的数据解析,插入到数据库中
int i = importExcelData(excelFileName,user);
if(i>0){
map.put("success", true);
map.put("count", i);
}else{
map.put("success", false);
}
} catch (Exception e) {
map.put("success", false);
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValueAsString(map);
} catch (JsonProcessingException e1) {
e1.printStackTrace();
}
return SUCCESS;
}
importExcelData方法
public int importExcelData(String excelFileName,UserVo user){
//定义一个标识位 表示插入了几条数据
int ret = 0;
String directory = "/upload/Excel";
String targetDirectory = ServletActionContext.getServletContext().getRealPath(directory);
File files = new File(targetDirectory,excelFileName);
try {
//将临时文件夹中的文件读取到内存中
FileInputStream fis = new FileInputStream(files);
//解析excel,把数据封装成List<MarketActivity>
HSSFWorkbook wb=new HSSFWorkbook(fis);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row=null;
HSSFCell cell=null;
MarketingActivities ma=null;
//创建一个承载实体的List集合
List<MarketingActivities> activityList = new ArrayList<MarketingActivities>();
//第一列为表头不需要,从第二列开始取数据 i=1
for(int i=1;i<=sheet.getLastRowNum();i++){
//每循环一次,为一个实体类对象的各个属性赋值
row=sheet.getRow(i);
ma=new MarketingActivities();
ma.setCreateBy("e52c4d4e2bc845ecadce6abc7b7765ac");
ma.setCreateTime(TimeUtil.getTime19());
ma.setId(UUIDUtils.get32UUID());
ma.setState("2e772213fe404ff8aa53db2a387d5db3");
ma.setType("129bf9c3dac34a588322d0fc83882b03");
ma.setOwner("e52c4d4e2bc845ecadce6abc7b7765ac");
for(int j=0;j<row.getLastCellNum();j++){
cell=row.getCell(j);
if(j==0){
ma.setName(cell.getStringCellValue());
}else if(j==1){
ma.setStartDate(cell.getStringCellValue());
}else if(j==2){
ma.setEndDate(cell.getStringCellValue());
}else if(j==3){
ma.setBudgetcost((int) cell.getNumericCellValue());
}else if(j==4){
ma.setActualcost((int) cell.getNumericCellValue());
}else if(j==5){
ma.setDescription(cell.getStringCellValue());
}
}
activityList.add(ma);
//每解析10条数据执行一次插入操作
if(i%10==0){
//保存一次
MarkActiveService markService = (MarkActiveService) ServiceFactory.getService(new MarkActiveServiceImpl());
ret+=markService.importExcelData(activityList);
activityList.clear();
}
}
if(activityList.size()>0){
MarkActiveService markService = (MarkActiveService) ServiceFactory.getService(new MarkActiveServiceImpl());
ret+=markService.importExcelData(activityList);
}
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
Map<String,Object> map = new HashMap<String,Object>();
public Map<String, Object> getMap() {
return map;
}
public void setMap(Map<String, Object> map) {
this.map = map;
}
html部分
<form id="uploadForm" enctype="multipart/form-data">
<input id="activityFile" type="file" name="excel">
</form>
js部分
<script type="text/javascript" src="jquery/jquery-1.11.1-min.js"></script>
<script type="text/javascript" src="jquery/jquery.form.js"></script>
$("#uploadForm").submit();
//ajaxForm提交表单数据
$("#uploadForm").ajaxForm({
url : "activity/uploadMarkActive.action",
dataType : "json",
type : "post",
resetForm : true,
beforeSubmit : function(){
//收集参数
var fileName=$("#activityFile").val();
var suffix=(fileName.substr(fileName.lastIndexOf(".")+1)).toUpperCase();
if(!(suffix=='XLS'||suffix=='XLSX')){
alert("只能上传XLS或者XLSX类型的文件!");
return false;
}
},
success : function(data){
if(data.success){
var count = data.count;
alert("导入成功!导入了 "+count+"条数据~");
$("#importActivityModal").modal("hide");
pageList(1,$("#myPageNation").bs_pagination('getOption', 'rowsPerPage'));
}else{
alert("导入失败!请检查文件格式!");
$("#importActivityModal").modal("show");
}
}
});
注:action方法中的private File excel 应该与表单中的name标签的值一致,以便struts调用拦截器进行文件上传