Как выборочно применять границы для таблицы docx в Apache POI? - PullRequest
0 голосов
/ 18 октября 2019

В Microsoft Word, если вы перейдете к свойствам таблицы, а затем к разделу «Границы и заливка», вы увидите, что вы можете применять границы к таблице по 8 ее аспектам. сверху, снизу, слева, справа, по центру, по горизонтали, по диагонали влево и по диагонали влево

Как их выборочно включить с помощью POI?

enter image description here

1 Ответ

2 голосов
/ 18 октября 2019

В текущем apache poi 4.1.0 класс XWPFTable предоставляет методы для этого.

Например, XWPFTable.setTopBorder :

public void setTopBorder(XWPFTable.XWPFBorderType type,
                         int size,
                         int space,
                         java.lang.String rgbColor)

Set Top borders for table

Parameters:
    type - - XWPFTable.XWPFBorderType e.g. single, double, thick
    size - - Specifies the width of the current border. The width of this border is 
             specified in measurements of eighths of a point, with a minimum value of two 
             (onefourth of a point) and a maximum value of 96 (twelve points). 
             Any values outside this range may be reassigned to a more appropriate value.
    space - - Specifies the spacing offset that shall be used to place this border 
              on the table
    rgbColor - - This color may either be presented as a hex value (in RRGGBB format), 
                 or auto to allow a consumer to automatically determine the border color 
                 as appropriate. 

См. XWPFTable.XWPFBorderType для возможных типов границ.

Полный пример:

import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;

public class CreateWordTableBorders {

 public static void main(String[] args) throws Exception {

  XWPFDocument document= new XWPFDocument();

  XWPFParagraph paragraph = document.createParagraph();
  XWPFRun run=paragraph.createRun();  
  run.setText("The table:");

  //create the table
  XWPFTable table = document.createTable(3,3);
  table.setWidth("100%");
  for (int row = 0; row < 3; row++) {
   for (int col = 0; col < 3; col++) {
    table.getRow(row).getCell(col).setText("row " + row + ", col " + col);
   }
  }

  //set borders
  table.setTopBorder(XWPFTable.XWPFBorderType.THICK_THIN_LARGE_GAP, 32, 0, "FF0000");
  table.setBottomBorder(XWPFTable.XWPFBorderType.THICK_THIN_LARGE_GAP, 32, 0, "FF0000");
  table.setLeftBorder(XWPFTable.XWPFBorderType.THICK_THIN_LARGE_GAP, 32, 0, "FF0000");
  table.setRightBorder(XWPFTable.XWPFBorderType.THICK_THIN_LARGE_GAP, 32, 0, "FF0000");
  table.setInsideHBorder(XWPFTable.XWPFBorderType.DOT_DASH, 16, 0, "00FF00");
  table.setInsideVBorder(XWPFTable.XWPFBorderType.DOTTED, 24, 0, "0000FF");

  paragraph = document.createParagraph();

  FileOutputStream fileOut = new FileOutputStream("create_table.docx"); 
  document.write(fileOut);
  fileOut.close();
  document.close();
 }
}
...