码迷,mamicode.com
首页 > 其他好文 > 详细

POI读取加密的EXCEL(兼容XLS,XLSX格式)

时间:2015-06-19 15:19:18      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

最近项目里需要读取加密的excel,有xls和xlsx两种类型,对于加解密apache官方网站有简要说明


需要的jar包poi-3.9,jar    poi-ooxml-3.9.jar  poi-ooxml-schemas-3.9.jar   xmlbeans-2.3.0.jar  dom4j-1.6.1.jar  


注意poi的3个jar版本号要对应,不然会有一些问题。

上代码咯~

    /**
     * Excel导入
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = {"importExcel"})
    @ResponseBody
    public Result importExcel(@RequestParam(value = "ym")String ym,@RequestParam(value = "filedata")MultipartFile file){
    	int count=0;
        Result result = null;
        try {
            if (file != null) {

        		String password = "5151";
        		String fileName=file.getOriginalFilename();
        		String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        		String yyyyMM=ym.replace("-", "");
        		
        		Workbook workbook;
        		//解密excel
        		if (prefix.toUpperCase().equals("XLS")) {
        			org.apache.poi.hssf.record.crypto.Biff8EncryptionKey
        					.setCurrentUserPassword(password);
        			workbook = WorkbookFactory.create(file.getInputStream());
        			file.getInputStream().close();
        		} else {
//        		    POIFSFileSystem pfs = newPOIFSFileSystem(POIDataSamples.getPOIFSInstance().openResourceAsStream("**.xlsx"));         		
        			POIFSFileSystem pfs = new POIFSFileSystem(file.getInputStream());
        			file.getInputStream().close();
        			EncryptionInfo encInfo = new EncryptionInfo(pfs);
        			Decryptor decryptor = Decryptor.getInstance(encInfo);
        			decryptor.verifyPassword(password);
            	    workbook = new XSSFWorkbook(decryptor.getDataStream(pfs));//不支持2007+的EXCEL
            	 // XSSFWorkbook workbook = new XSSFWorkbook(decryptor.getDataStream(pfs));//支持2007+的EXCEL
        		}
                //读取excel数据
        		Sheet sheet = workbook.getSheetAt(0);	<span style="font-family: Arial, Helvetica, sans-serif;">//不支持2007+的EXCEL</span>
//	                XSSFSheet sheet = workbook.getSheetAt(0);	支持2007+的excel



POI读取加密的EXCEL(兼容XLS,XLSX格式)

标签:

原文地址:http://blog.csdn.net/x2145637/article/details/46561051

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!