poi实现excel读取超链接,图片,页眉页脚,文本框.

Shaka 7月前 ⋅ 545 阅读

 

最近需要用到这几个知识,不是很好找,所以贴出来备用.

1.设置页眉页脚.

//设置页眉
Header header = sheet.getHeader();
header.setCenter("页眉中间文字");
header.setLeft("页眉左侧文字");
header.setRight("页眉右侧文字");

页脚同理.

2.处理图形和富文本(文本框)

//处理sheet中的图形
XSSFDrawing xssfPatriarch = sheet.getDrawingPatriarch();
List shapes = xssfPatriarch.getShapes();

  处理图形

dataMap = new HashMap<String, List>();
List pictureDataList;
for (XSSFShape sp : shapes) {
if (sp instanceof XSSFPicture) {
XSSFPicture picture = (XSSFPicture) sp;
//获取图片数据
XSSFPictureData pictureData = picture.getPictureData();
//图形定位
XSSFClientAnchor anchor = picture.getClientAnchor();
int row1 = anchor.getRow1();
String rowNum = String.valueOf(row1);
XSSFPictureData picData = picture.getPictureData();
byte[] data = picData.getData();
if (dataMap.get(rowNum) != null) {
pictureDataList = dataMap.get(rowNum);
} else {
pictureDataList = new ArrayList();
}
pictureDataList.add(pictureData);
dataMap.put(rowNum, pictureDataList);
int row2 = anchor.getRow2();
short col1 = anchor.getCol1();
short col2 = anchor.getCol2();
int dx1 = anchor.getDx1();
int dx2 = anchor.getDx2();
int dy1 = anchor.getDy1();
int dy2 = anchor.getDy2();
XSSFClientAnchor newAnchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
newAnchor.setAnchorType(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE);
XSSFDrawing patriarch = createSheet.createDrawingPatriarch();
patriarch.createPicture(newAnchor, workbook.addPicture(data, picData.getPictureType()));
}
}

 处理文本框

if (sp instanceof XSSFSimpleShape) {
XSSFSimpleShape xss = (XSSFSimpleShape) sp;
//获取富文本值
String textBoxText = xss.getText();
//富文本图形定位
XSSFClientAnchor anchor = (XSSFClientAnchor) xss.getAnchor();
int row1 = anchor.getRow1();
int row2 = anchor.getRow2();
short col1 = anchor.getCol1();
short col2 = anchor.getCol2();
int dx1 = anchor.getDx1();
int dx2 = anchor.getDx2();
int dy1 = anchor.getDy1();
int dy2 = anchor.getDy2();
XSSFClientAnchor newAnchor = new XSSFClientAnchor(dx1, dy1, dx2, dy2, col1, row1, col2, row2);
newAnchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
XSSFDrawing patriarch = createSheet.createDrawingPatriarch();
XSSFSimpleShape xssfSimpleShape = patriarch.createSimpleShape(newAnchor);
xssfSimpleShape.addNewTextParagraph(textBoxText);
xssfSimpleShape.setTextAutofit(TextAutofit.SHAPE);
xssfSimpleShape.setShapeType(xss.getShapeType());
}

3.设置超链接

//设置超链接
XSSFHyperlink link = fromCell.getHyperlink();
if (link != null) {
toCell.setHyperlink(link);
}

注意:本文归作者所有,未经作者允许,不得转载

全部评论: 0

    我有话说: