excel上传+解析

对于excel上传,我们需要做几方面的配置,包括jsp,springmvc.xml,pom.xml,controller中做相关配置,对于excel的格式还有xls和xlsx的区别,所以,我采用的是jxl--xls,poi--xlsx,下面的是相关配置

pom.xml

<!-- excel文件上传 -->
		<dependency>
		    <groupId>commons-fileupload</groupId>
		    <artifactId>commons-fileupload</artifactId>
		    <version>1.2.1</version>
		</dependency>
		<dependency>
		    <groupId>commons-io</groupId>
		    <artifactId>commons-io</artifactId>
		    <version>2.4</version>
		</dependency>
<!-- Excel操作相关jar -->
		<dependency>
			<groupId>net.sourceforge.jexcelapi</groupId>
			<artifactId>jxl</artifactId>
			<version>2.6.12</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.10.1</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml</artifactId>
		    <version>3.8</version>
		</dependency>
		<dependency>
		    <groupId>org.apache.poi</groupId>
		    <artifactId>poi-ooxml-schemas</artifactId>
		    <version>3.8</version>
		</dependency>
jsp

<input type="file" id="file" name="file" />
<input type="button" id="upload" value="上传文件" />

在jsp中要引入:ajaxfileupload.js  下载

js

//向后台上传Excel数据

function ajaxFileUpload() {
	debugger;
	var fileName = $("#file").val();
	
	if(fileName==null || fileName==""){
		alert("请选择文件!");
		return;
	}
	var fileSuffixArray = fileName.split('.');
	if(!(fileSuffixArray[1] == 'xls' || fileSuffixArray[1] == 'xlsx')){
		alert("文件格式错误,请上传Excel文件!");
		return;
	}
    var url = "<%=path%>/data/uploadExcelData";
    var method = "method=fileUpload"
    $.ajaxFileUpload({
        url : url,
        secureuri : false,
        fileElementId : 'file',
        dataType : 'text',
        success : function(data, status) {
            if (data == "exist") {
                alert("该文件已经存在请勿重复上传");
            }
            if (data == "success") {
                alert("文件上传成功");
            }
            if (data == "fail") {
                alert("文件上传失败,请重新上传");
            }
        },
        error : function() {

        }
    });
}
springmvc.xml

<!-- 5,支持上传文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
controller

public  ModelAndView uploadExcelData(HttpServletRequest request,MultipartFile file) throws IOException{
		try {
			String filename = file.getOriginalFilename();
			String[] split = filename.split("\\.");
			if("xls".equals(split[1])) {
				ExcelUtil.excelToData(file);
			}else if("xlsx".equals(split[1])) {
				ExcelUtil.excelToDataNew(file);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		ModelAndView md = new ModelAndView();
		return md;
	}


}
ExcelUtil

/**
	 * @Description 将excel变为实体类对象集合:(.xls)
	 *                                 1: 想使用时,直接将它赋值到相应位置,将1和2和3补齐即可
	 *                                 2: excel需要使用特定版本的,2003的好用(其余未验证)
	 *                                 3: 此方法不可直接调用,使用时需要将核心代码复制到相应位置使用
	 * @param request
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws BiffException
	 */
	public static List excelToData(MultipartFile file) throws IOException, BiffException{
		List list = new ArrayList();
		//获取输入流
		InputStream in = file.getInputStream();
		// 创建一个新的写入工作簿 
		Workbook book = Workbook.getWorkbook(in);
		//获取第一个sheet页
		Sheet sheet = book.getSheet(0);  
		//获取Sheet表中所包含的总列数
		int rsColumns = sheet.getColumns();
		//获取Sheet表中所包含的总行数
		int rsRows = sheet.getRows();
		//获取指定单元格的对象引用
		for(int i=1;i<rsRows;i++){
			//1,(需要补充的地方)创建实体类对象

			for(int j=0;j<rsColumns;j++){
				Cell cell = sheet.getCell(j,i);
				String contents = cell.getContents();
				if(contents != null&&"".equals(contents.trim())) {
					//2,(需要补充的地方)然后就根据实体类的属性进行赋值了
				}
				
			}
			
			//3,(需要补充的地方)将对象放入集合中
		}
		book.close();// 关闭 


		return list;
	}

	/**
	 * @Description 将excel变为实体类对象集合:(.xlsx)
	 *                                 1: 想使用时,直接将它赋值到相应位置,将1和2和3补齐即可
	 *                                 2: excel需要使用特定版本的,2007的好用(其余未验证)
	 *                                 3: 此方法不可直接调用,使用时需要将核心代码复制到相应位置使用
	 * @param request
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws BiffException
	 */
	public static List excelToDataNew(MultipartFile file){
		List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();  
        // IO流读取文件  
        InputStream input = null;  
        XSSFWorkbook wb = null;  
        ArrayList<String> rowList = null;  
        try {  
            input = file.getInputStream();  
            // 创建文档  
            wb = new XSSFWorkbook(input);                         
            //读取sheet(页)  
            for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){  
                XSSFSheet xssfSheet = wb.getSheetAt(numSheet);  
                if(xssfSheet == null){  
                    continue;  
                }  
                int  totalRows = xssfSheet.getLastRowNum();                
                //读取Row,从第二行开始  
                for(int rowNum = 1;rowNum <= totalRows;rowNum++){  
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);  
                    if(xssfRow!=null){  
                        rowList = new ArrayList<String>();  
                        int   totalCells = xssfRow.getLastCellNum();  
                        //读取列,从第一列开始  
                        for(int c=0;c<=totalCells+1;c++){  
                            XSSFCell cell = xssfRow.getCell(c);  
                            if(cell==null){  
                            	//当cell值为null时如何处理
//                                rowList.add(ExcelUtil.EMPTY);  
                                continue;  
                            }  
                            //当cell值不为null时如何处理
//                            rowList.add(ExcelUtil.getXValue(cell).trim());  
                        }     
                    list.add(rowList);                                            
                    }  
                }  
            }  
            return list;  
        } catch (IOException e) {             
            e.printStackTrace();  
        } finally{  
            try {  
                input.close();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return null;  
		
	}








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值