Struts2+poi實現Excel檔案上傳並插入資料庫的操作
阿新 • • 發佈:2019-01-06
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呼叫攔截器進行檔案上傳