天天看点

SpringMVC file上传excel文件到html页面显示后加入数据库

html   enctype="multipart/form-data"

选择导入文件 
         
          
         
         
         
       
						
       

	
      
	
     
	
    
	
   
           

js   var formData = new FormData($( "#fileform" )[0]); 发送数据格式

$(function() {
	var delaytime = 1;
	$("#aa").click(function(){
		$('#file').click()
	});

	
	
	$("#file").change(function(){
		
		var formData = new FormData($( "#fileform" )[0]);  
		$.ajax({  
			url: "apply/file" ,  
			type: "POST",
			data: formData,  
			async: false,  
			cache: false,  
			contentType: false,   // 告诉jQuery不要去设置Content-Type请求头 
			processData: false,   // 告诉jQuery不要去处理发送的数据
			success: function (data) {  
				setTimeout(showPreValue(data.data), delaytime); 
			},  
			error: function (returndata) {  
				alert(returndata);  
			}
			});  
		
		
		
		
		
		
	});
})
	
           

controller   获取字节流将文件存放在服务器固定位置,并从固定位置开始解析文件

@RequestMapping(value = "/file", method = RequestMethod.POST)
	     public @ResponseBody AjaxResult batchimport(@RequestParam(value="file") MultipartFile file,
	             HttpServletRequest request,HttpServletResponse response) throws Exception{
		  AjaxResult result = null;
		  System.out.println("fileName--->"+file.getOriginalFilename());  
	        if(!file.isEmpty()){  
	            	String path=file.getOriginalFilename();
	            	System.out.println(path+"-------------------------------");
	                FileOutputStream os = new FileOutputStream("D:/"+file.getOriginalFilename());  
	                InputStream in = file.getInputStream();  
	                int b=0;  
	                while((b=in.read())!=-1){  
	                    os.write(b);  
	                }  
	                os.flush();  
	                os.close();  
	                in.close(); 
	                
	                String excel="D:/"+path;
	                System.out.println(excel+"--------------------------------");
	                
	                Object[] data = new Object[2];
	                data = new ReadExcel().readExcel(excel);
	                if (null != data) {
	    				result = new AjaxResult(1, data);
	    			} else {
	    				result = new AjaxResult(0, "修改失败!");
	    			}
	                result.setData(data);
	                
	           
	     } 
	        return result;
	  } 
	
           

readExcel   

/**
 * 
 */
package org.zzsc.auth.apply.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.zzsc.auth.apply.model.TApply;
import org.zzsc.auth.apply.model.TApplyEnterprice;


/**
 * @author Hongten
 * @created 2014-5-20
 */
public class ReadExcel {
    
    /**
     * read the Excel file
     * @param path the path of the Excel file
     * @return
     * @throws IOException
     */
    public Object[] readExcel(String path) throws IOException {
        if (path == null || Common.EMPTY.equals(path)) {
            return null;
        } else {
            String postfix = Util.getPostfix(path);
            if (!Common.EMPTY.equals(postfix)) {
                if (Common.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)) {
                    return readXls(path);
                } else if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
                    return readXlsx(path);
                }
            } else {
                System.out.println(path + Common.NOT_EXCEL_FILE);
            }
        }
        return null;
    }

    /**
     * Read the Excel 2010
     * @param path the path of the excel file
     * @return
     * @throws IOException
     */
    @SuppressWarnings("null")
	public Object[] readXlsx(String path) throws IOException {
        System.out.println(Common.PROCESSING + path);
        InputStream is = new FileInputStream(path);
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        TApply apply = null;
        TApplyEnterprice tApplyEnterprice=null;
        //存放俩对象
        Object[] data = new Object[2];
		
        // Read the Sheet
        for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                if (xssfRow != null) {
                	apply=new TApply();
                	tApplyEnterprice=new TApplyEnterprice();
                    XSSFCell applyCode = xssfRow.getCell(0);
                    XSSFCell applyDate = xssfRow.getCell(1);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    				String date=sdf.format(HSSFDateUtil.getJavaDate(applyDate.getNumericCellValue())).toString();
                    XSSFCell qltType= xssfRow.getCell(2);
                    XSSFCell qltLevel = xssfRow.getCell(3);
                    XSSFCell applyType = xssfRow.getCell(4);
                    XSSFCell applyCategory= xssfRow.getCell(5);
                    XSSFCell entName= xssfRow.getCell(6);
                    XSSFCell province = xssfRow.getCell(7);
                    apply.setapplyCode(getValue(applyCode));
                    apply.setApplyDate(date);
                    apply.setQltType(getValue(qltType));
                    apply.setQltLevel(getValue(qltLevel));
                    apply.setApplyType(getValue(applyType));
                    apply.setApplyCategory(getValue(applyCategory));
                    apply.setEntName(getValue(entName));
                    apply.setProvince(getValue(province));
                    tApplyEnterprice.setApplyCode(getValue(applyCode));
                    tApplyEnterprice.setEntName(getValue(entName));
                    tApplyEnterprice.setProvince(getValue(province));
                }
            }
        }
        data[0] = apply;
		data[1] = tApplyEnterprice;
        return data;
    }

    /**
     * Read the Excel 2003-2007
     * @param path the path of the Excel
     * @return
     * @throws IOException
     */
    public Object[] readXls(String path) throws IOException {
        System.out.println(Common.PROCESSING + path);
        InputStream is = new FileInputStream(path);
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
        TApply apply = null;
        TApplyEnterprice tApplyEnterprice=null;
        
      //存放俩对象
        Object[] data = new Object[2];
        // Read the Sheet
        for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // Read the Row
            for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow != null) {
                	apply=new TApply();
                	tApplyEnterprice=new TApplyEnterprice();
                    HSSFCell applyCode = hssfRow.getCell(0);
                    HSSFCell applyDate = hssfRow.getCell(1);
                    HSSFCell qltType = hssfRow.getCell(2);
                    HSSFCell qltLevel = hssfRow.getCell(3);
                    HSSFCell applyType = hssfRow.getCell(3);
                    HSSFCell applyCategory = hssfRow.getCell(3);
                    HSSFCell entName = hssfRow.getCell(3);
                    HSSFCell province = hssfRow.getCell(3);
                    apply.setapplyCode(getValue(applyCode));
                    apply.setApplyDate(getValue(applyDate));
                    apply.setQltType(getValue(qltType));
                    apply.setQltLevel(getValue(qltLevel));
                    apply.setApplyType(getValue(applyType));
                    apply.setApplyCategory(getValue(applyCategory));
                    apply.setEntName(getValue(entName));
                    apply.setProvince(getValue(province));
                    tApplyEnterprice.setApplyCode(getValue(applyCode));
                    tApplyEnterprice.setEntName(getValue(entName));
                    tApplyEnterprice.setProvince(getValue(province));
                }
            }
        }
        data[0] = apply;
		data[1] = tApplyEnterprice;
        return data;
    }

    @SuppressWarnings("static-access")
    private String getValue(XSSFCell xssfRow) {
        if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfRow.getBooleanCellValue());
        } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
            return String.valueOf(xssfRow.getNumericCellValue());
        } else {
            return String.valueOf(xssfRow.getStringCellValue());
        }
    }

    @SuppressWarnings("static-access")
    private String getValue(HSSFCell hssfCell) {
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            return String.valueOf(hssfCell.getNumericCellValue());
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
}
           
/**
 * 
 */
package org.zzsc.auth.apply.file;

/**
 * @author Hongten
 * @created 2014-5-21
 */
public class Common {

    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";

    public static final String EMPTY = "";
    public static final String POINT = ".";
    public static final String LIB_PATH = "lib";
    public static final String STUDENT_INFO_XLS_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2003_POSTFIX;
    public static final String STUDENT_INFO_XLSX_PATH = LIB_PATH + "/student_info" + POINT + OFFICE_EXCEL_2010_POSTFIX;
    public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
    public static final String PROCESSING = "Processing...";

}
           
/**
 * 
 */
package org.zzsc.auth.apply.file;


/**
 * @author Hongten
 * @created 2014-5-21
 */
public class Util {

    /**
     * get postfix of the path
     * @param path
     * @return
     */
    public static String getPostfix(String path) {
        if (path == null || Common.EMPTY.equals(path.trim())) {
            return Common.EMPTY;
        }
        if (path.contains(Common.POINT)) {
            return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());
        }
        return Common.EMPTY;
    }
}