poi 删除页眉页脚
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
代码
/**
* 清理页眉页脚
* @param inputStream
* @param extension
* @return
*/
private static InputStream clearHeaderAndFooter(InputStream inputStream,String extension){
if("doc".equals(extension)){
return clearDocHeaderAndFooter(inputStream);
}
if("docx".equals(extension)){
return clearDocxHeaderAndFooter(inputStream);
}
return null;
}
/**
* 清理docx 类型页眉页脚
* @param inputStream
*/
private static InputStream clearDocxHeaderAndFooter(InputStream inputStream) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
XWPFDocument document = new XWPFDocument(inputStream);
document.getHeaderList().forEach(XWPFHeaderFooter::clearHeaderFooter);
document.getFooterList().forEach(XWPFHeaderFooter::clearHeaderFooter);
document.write(baos);
return new ByteArrayInputStream(baos.toByteArray());
}catch (Exception e){
log.error("清理页眉页脚异常 error:{}",e.getMessage(),e);
throw new RuntimeException("文档解析异常");
}finally {
IoUtil.close(baos);
}
}
/**
* 清理doc 页眉页脚
* @param inputStream
*/
private static InputStream clearDocHeaderAndFooter(InputStream inputStream) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try{
HWPFDocument document = new HWPFDocument (inputStream);
HeaderStories headerStories = new HeaderStories(document);
deleteRange(headerStories.getEvenFooterSubrange());
deleteRange(headerStories.getOddFooterSubrange());
deleteRange(headerStories.getFirstFooterSubrange());
deleteRange(headerStories.getEvenHeaderSubrange());
deleteRange(headerStories.getOddHeaderSubrange());
deleteRange(headerStories.getFirstHeaderSubrange());
document.write(baos);
return new ByteArrayInputStream(baos.toByteArray());
}catch (Exception e){
log.error("清理页眉页脚异常 error:{}",e.getMessage(),e);
throw new RuntimeException("文档解析异常");
}finally {
IoUtil.close(baos);
}
}
private static void deleteRange(Range range){
if(range != null){
range.delete();
}
}