使用xssf库在Excel中使用箭头绘制线条

时间:2015-12-31 07:01:46

标签: java excel apache-poi xssf

我想以编程方式在Excel工作表中绘制一条带箭头的线,我能够创建该线但不能创建箭头。 这是我的代码,我需要改变我想要的东西;

XSSFSimpleShape shape = drawing.createSimpleShape(a);
shape.setShapeType(ShapeTypes.LINE);
shape.setLineWidth(1.5);
shape.setLineStyle(3);

我也尝试使用shape.setShapeType(ShapeTypes.LEFT_ARROW); shape.setShapeType(ShapeTypes.RIGHT_ARROW);shape.setShapeType(ShapeTypes.UP_ARROW);,但这对我没有帮助。

这就是我所拥有的:

enter image description here

这就是我想要的: enter image description here

1 个答案:

答案 0 :(得分:3)

{ap} POI中Drawing支持似乎不是很完整。因此需要使用底层对象。

在Excel中,箭头是该行的头端或尾端属性。

示例:

import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;

import java.io.FileOutputStream;
import java.io.IOException;

import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.CTLineProperties; 
import org.openxmlformats.schemas.drawingml.x2006.main.CTLineEndProperties;
import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndType;
import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndLength;
import org.openxmlformats.schemas.drawingml.x2006.main.STLineEndWidth;

class ShapeArrow {

 public static void main(String[] args) {
  try {

   Workbook wb = new XSSFWorkbook();

   Sheet sheet = wb.createSheet("Sheet1");

   CreationHelper helper = wb.getCreationHelper();
   Drawing drawing = sheet.createDrawingPatriarch();

   ClientAnchor anchor = helper.createClientAnchor();
   anchor.setCol1(2);
   anchor.setRow1(2); 
   anchor.setCol2(5);
   anchor.setRow2(5); 

   XSSFSimpleShape shape = ((XSSFDrawing)drawing).createSimpleShape((XSSFClientAnchor)anchor);
   shape.setShapeType(ShapeTypes.LINE);
   shape.setLineWidth(1.5);
   shape.setLineStyle(3);
   shape.setLineStyleColor(0,0,255);

//apache POI sets first shape Id to 1. It should be 0.
shape.getCTShape().getNvSpPr().getCNvPr().setId(shape.getCTShape().getNvSpPr().getCNvPr().getId()-1);

   CTShapeProperties shapeProperties = shape.getCTShape().getSpPr();
   CTLineProperties lineProperties = shapeProperties.getLn();

   CTLineEndProperties lineEndProperties = org.openxmlformats.schemas.drawingml.x2006.main.CTLineEndProperties.Factory.newInstance();
   lineEndProperties.setType(STLineEndType.TRIANGLE);
   lineEndProperties.setLen(STLineEndLength.LG);
   lineEndProperties.setW(STLineEndWidth.LG);

   lineProperties.setHeadEnd(lineEndProperties);

   FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
   wb.write(fileOut);

  } catch (IOException ioex) {
  }
 }
}

在POI中,有一个XSSFShape.getCTShape()方法可以获取CTShape个对象。但是有了这个,我们就失去了POI文档。请参阅http://grepcode.com/file/repo1.maven.org/maven2/org.apache.poi/ooxml-schemas/1.1/org/openxmlformats/schemas/drawingml/x2006/spreadsheetDrawing/CTShape.java了解文档。