標籤:poi excel
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包
POI 操作Excel 異常org.apache.poi.openxml4j.exceptions.invalidformatexception: package should contain a c