通过ajax上传excel

html:

<li>
         <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;传:</span>
         <span class="input">
   <input type="file" id="upfile" name="upfile" placeholder=""/>
</span>
         <button onclick="importExp();">导入</button>
         <span>格式:.xls</span>
     </li>
js:
//导入文件 function importExp() {
    var formData = new FormData();
    var name = $("#upfile").val();
    formData.append("file",$("#upfile")[0].files[0]);
    formData.append("name",name);
    $.ajax({
        url : '#springUrl('')/summary/importExp',type : 'POST',async : false,data : formData,// 告诉jQuery不要去处理发送的数据  processData : false,// 告诉jQuery不要去设置Content-Type请求头  contentType : false,beforeSend:function(){
            console.log("正在进行,请稍候");
        },success : function(responseStr) {
            if(responseStr=="01"){
                alert("导入成功");
            }else{
                alert("导入失败");
            }
        }
    });
}

controller:

@RequestMapping("/importExp")
@ResponseBody
public String importExp(@RequestParam("file") MultipartFile file,HttpServletRequest request){
// 判断文件是否为空
String flag = "02";//上传标志
if (!file.isEmpty()) {
try {
String originalFilename = file.getOriginalFilename();//原文件名字
InputStream is = file.getInputStream();//获取输入流
flag = summaryExpServiceImpl.writeExelData(is);
// 转存文件
//file.transferTo(new File(filePath));
} catch (Exception e) {
flag="03";//上传出错
e.printStackTrace();
}
}
return flag;
}



service:

/**  * 写入  * @param is  */ public String writeExelData(InputStream is){
    List<List<String>> list = readExcelContent(is);
    for (int i=0,j=list.size();i<j;i++){
        List<String> row = list.get(i);
        ExpInfoSummary expInfoSummary = new ExpInfoSummary();
        expInfoSummary.setOrgName(row.get(0));
        expInfoSummary.setSiteName(row.get(1));
        expInfoSummary.setProductCode(row.get(2));
        expInfoSummary.setProductName(row.get(3));
        expInfoSummary.setProductNum(row.get(4));
        expInfoSummary.setProductPrice(Double.valueOf(row.get(5)));
        expInfoSummary.setProductState(row.get(6));
        pool.getSqlSession("psEpfSqlSession").selectList("com.jd.ps.data.epf.mapper.expInfoSummary.insertExp",expInfoSummary);
    }
    return "01";
}

/**  * 读取Excel数据内容  * @param is  * @return Map 包含单元格数据内容的Map对象  */ public List<List<String>> readExcelContent(InputStream is) {
    List<List<String>> content = new ArrayList<List<String>>();
    POIFSFileSystem fs;
    HSSFWorkbook wb;
    HSSFSheet sheet;
    HSSFRow row;
    String str = "";
    try {
        fs = new POIFSFileSystem(is);
        wb = new HSSFWorkbook(fs);
        sheet = wb.getSheetAt(0);
        // 得到总行数  int rowNum = sheet.getLastRowNum();
        row = sheet.getRow(0);
        int colNum = row.getPhysicalNumberOfCells();
        // 正文内容应该从第二行开始,第一行为表头的标题  for (int i = 1; i <= rowNum; i++) {
            row = sheet.getRow(i);
            int j = 0;
            List<String> list = new ArrayList<String>();
            while (j < colNum) {
                // 每个单元格的数据内容用"-"分割开,以后需要时用String类的replace()方法还原数据  // 也可以将每个单元格的数据设置到一个javabean的属性中,此时需要新建一个javabean  // str += getStringCellValue(row.getCell((short) j)).trim() +  // "-";  str = getCellFormatValue(row.getCell((short) j)).trim();
                list.add(str);
                j++;
            }
            content.add(list);
            str = "";
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

/**  * 根据HSSFCell类型设置数据  * @param cell  * @return  */ private String getCellFormatValue(HSSFCell cell) {
    String cellvalue = "";
    if (cell != null) {
        // 判断当前Cell的Type  switch (cell.getCellType()) {
            // 如果当前Cell的Type为NUMERIC  case HSSFCell.CELL_TYPE_NUMERIC:
            case HSSFCell.CELL_TYPE_FORMULA: {
                // 判断当前的cell是否为Date  if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    // 如果是Date类型则,转化为Data格式   //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00  //cellvalue = cell.getDateCellValue().toLocaleString();   //方法2:这样子的data格式是不带带时分秒的:2011-10-12  Date date = cell.getDateCellValue();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    cellvalue = sdf.format(date);

                }
                // 如果是纯数字  else {
                    // 取得当前Cell的数值  cellvalue = String.valueOf(cell.getNumericCellValue());
                }
                break;
            }
            // 如果当前Cell的Type为STRIN  case HSSFCell.CELL_TYPE_STRING:
                // 取得当前的Cell字符串  cellvalue = cell.getRichStringCellValue().getString();
                break;
            // 默认的Cell值  default:
                cellvalue = " ";
        }
    } else {
        cellvalue = "";
    }
    return cellvalue;

}

相关文章

$.AJAX()方法中的PROCESSDATA参数 在使用jQuery的$.ajax()方...
form表单提交的几种方式 表单提交方式一:直接利用form表单提...
文章浏览阅读1.3k次。AJAX的无刷新机制使得在注册系统中对于...
文章浏览阅读1.2k次。 本文将解释如何使用AJAX和JSON分析器在...
文章浏览阅读2.2k次。/************************** 创建XML...
文章浏览阅读3.7k次。在ajax应用中,通常一个页面要同时发送...