POI 操作Excel 异常org.apache.poi.openxml4j.exceptions.invalidformatexception: package should contain a c

POI 操作Excel 出现如下异常

org.apache.poi.openxml4j.exceptions.invalidformatexception: package should contain a content type part 

代码如下
  public boolean parseToExcel(String oldFileName,String newFileName){
    Map<Object,Object> map = new HashMap<Object,Object>();
        map.put(0,"FYMC");
        map.put(1,"GXFYS");
        map.put(2,"LS_YSJGYS");
        map.put(4,"LS_ZDHJAJS");
        map.put(5,"LS_CGRKAJS");
        map.put(6,"LS_RKSBAJS");
        map.put(7,"LS_XSAJS");
        map.put(8,"LS_YJAJS");
        map.put(9,"LS_FYS");
        map.put(10,"SS_XSAJS");
        map.put(11,"SS_YJAJS");
        map.put(12,"SS_FYS");
        List<Map<String,String>> parseList = getDwgroupdtbgParse();
        //读取模板路径
        File filePath = new File(oldFileName);
        try {
            //读取Excel模板 
            Wrokbook dd = WorkbookFactory.create(new FileInputStream(filePath));    //此句抛出异常
           // Workbook wb = createworkbook(new FileInputStream(filePath));
        //读取模板内所有sheet内容
        Sheet sheet = wb.getSheetAt(0);
        for (int i = EXCEL_START_ROW; i < EXCEL_ROW_NUMS; i++) {
        // Row row =  sheet.getRow(i);  
        Row row = sheet.createRow(i);
        for (int j = 0; j < EXCEL_CELL_NUMS; j++) {
        Cell cell =  row.createCell(j+1); 
        if(j!=NO_CREATE_CELL){
        cell.setCellValue(String.valueOf(parseList.get(i-EXCEL_START_ROW).get(map.get((Object)j))));
        }
        }
        }
        //修改模板内容导出新模板
        FileOutputStream out = new FileOutputStream(newFileName);
        wb.write(out);
        out.close();
        return true;
        } catch (InvalidFormatException e) {
        e.printStackTrace();
        return false;
        } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
        } catch (IOException e) {
        e.printStackTrace();
        return false;
        }
}

解决办法是:workbook对象不从WorkbookFactory类中获取,单独写一个方法获得Workbook对象即可
代码如下:

 /**
    * 静态方法  解决创建Workbook 创建产生的问题
    * @param inp
    * @return
    * @throws IOException
    * @throws InvalidFormatException
    */
   public static Workbook createworkbook(InputStream inp) throws IOException,InvalidFormatException {
       if (!inp.markSupported()) {
           inp = new PushbackInputStream(inp, 8);
       }
       if (POIFSFileSystem.hasPOIFSHeader(inp)) {
           return new HSSFWorkbook(inp);
       }
       if (POIXMLDocument.hasOOXMLHeader(inp)) {
           return new XSSFWorkbook(OPCPackage.open(inp));
       }
       throw new IllegalArgumentException("你的excel版本目前poi解析不了");
   }

这是POI 操作Excel 所要用到的所有jar包
技术文章
文章来自:http://blog.csdn.net/u011598529/article/details/39233393
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3