Я пытаюсь создать заголовок ниже с помощью XWPFDocument и слияния ячеек - PullRequest
0 голосов
/ 02 ноября 2019

Я пытаюсь создать указанный ниже заголовок с помощью XWPFDocument и объединяющих ячеек.

Ниже на рисунке показано изображение для заголовка, который я пытаюсь создать

enter image description here

*XWPFDocument document = new XWPFDocument();
XWPFTable table = document.createTable(1, 8);*
CTTblBorders borders = table.getCTTbl().getTblPr().addNewTblBorders();
borders.addNewBottom().setVal(STBorder.THICK);
borders.addNewLeft().setVal(STBorder.NONE);
borders.addNewRight().setVal(STBorder.NONE);
borders.addNewTop().setVal(STBorder.THICK);
borders.addNewInsideV().setVal(STBorder.THICK);
table.getCTTbl().getTblPr().setTblBorders(borders);
table.setWidth(1440);

for (int col = 0 ; col < 8; col++) {
CTTblWidth tblWidth = table.getRow(0).getCell(col).getCTTc().addNewTcPr().addNewTcW();
tblWidth.setW(BigInteger.valueOf(1440));
//STTblWidth.DXA is used to specify width in twentieths of a point.
tblWidth.setType(STTblWidth.DXA);
}    
**mergeCellHorizontally(table, 0, 0, 1);**
XWPFTableCell cell = table.getRow(0).getCell(1);
CTTcPr ctTcPr = cell.getCTTc().getTcPr();
CTTcBorders ctTcBorders = ctTcPr.addNewTcBorders();
ctTcBorders.addNewRight().setVal(STBorder.NONE);
ctTcBorders.addNewBottom().setVal(STBorder.NONE);

1 Ответ

0 голосов
/ 02 ноября 2019

Первый вопрос для таких проблем с таблицами: всегда, сколько столбцов будет в таблице максимум? Или другими словами: сколько столбцов считает строку, имеющую наибольшее количество столбцов в таблице? Если этот ответ известен, то должна быть создана таблица с максимальным количеством столбцов. Все остальное будет возможно путем установки ширины столбцов, границ ячеек и / или слияния ячеек.

Но в вашем особом случае я не вижу, как слияние ячеек может помочь. Если предположить, что максимальное количество столбцов равно 8, тогда создание таблицы образцов будет возможно путем установки ширины столбцов и границ ячеек.

Пример:

import java.io.File;
import java.io.FileOutputStream;

import java.math.BigInteger;

import org.apache.poi.xwpf.usermodel.*;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

public class CreateWordTableSpecial {

 static void setColumnWidth(XWPFTable table, int row, int col, int width) {
  CTTblWidth tblWidth = CTTblWidth.Factory.newInstance();
  tblWidth.setW(BigInteger.valueOf(width));
  tblWidth.setType(STTblWidth.DXA);
  CTTcPr tcPr = table.getRow(row).getCell(col).getCTTc().getTcPr();
  if (tcPr != null) {
   tcPr.setTcW(tblWidth);
  } else {
   tcPr = CTTcPr.Factory.newInstance();
   tcPr.setTcW(tblWidth);
   table.getRow(row).getCell(col).getCTTc().setTcPr(tcPr);
  }
 }

 static void setCellBorders(XWPFTableCell cell, STBorder.Enum[] borderTypesLTRB) {
  CTTcBorders borders = CTTcBorders.Factory.newInstance();
  borders.addNewLeft().setVal(borderTypesLTRB[0]);
  borders.addNewTop().setVal(borderTypesLTRB[1]);
  borders.addNewRight().setVal(borderTypesLTRB[2]);
  borders.addNewBottom().setVal(borderTypesLTRB[3]);
  CTTcPr tcPr = cell.getCTTc().getTcPr();
  if (tcPr != null) {
   tcPr.setTcBorders(borders);
  } else {
   tcPr = CTTcPr.Factory.newInstance();
   tcPr.setTcBorders(borders);
   cell.getCTTc().setTcPr(tcPr);
  }
 }

 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 table
  XWPFTable table = document.createTable(3, 8);
  table.setWidth(1*1440*8); // table width = 8 inches

  //defining the column widths for the grid
  //column width values are in unit twentieths of a point (1/1440 of an inch)
  int defaultColWidth = 1*1440*8/8; // 8 columns fits to 8 inches 

  int[] colunmWidths = new int[] {
   defaultColWidth*3/4, defaultColWidth*2/4, defaultColWidth*8/4, defaultColWidth*3/4, 
   defaultColWidth*3/4, defaultColWidth*2/4, defaultColWidth*8/4, defaultColWidth*3/4
  };

  //create CTTblGrid for this table with widths of the 8 columns. 
  //necessary for Libreoffice/Openoffice to accept the column widths.
  //first column
  table.getCTTbl().addNewTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[0]));
  setColumnWidth(table, 0, 0, colunmWidths[0]);
  //other columns
  for (int col = 1; col < colunmWidths.length; col++) {
   table.getCTTbl().getTblGrid().addNewGridCol().setW(BigInteger.valueOf(colunmWidths[col]));
   setColumnWidth(table, 0, col, colunmWidths[col]);
  }

  //set cell borders
  for (int col = 0; col < 3; col++) {
   setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[] {STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL}); 
  } 
  setCellBorders(table.getRow(0).getCell(3), new STBorder.Enum[] {STBorder.NIL, STBorder.THICK, STBorder.THICK, STBorder.NIL}); 
  setCellBorders(table.getRow(0).getCell(4), new STBorder.Enum[] {STBorder.THICK, STBorder.THICK, STBorder.NIL, STBorder.NIL}); 
  for (int col = 5; col < 8; col++) {
   setCellBorders(table.getRow(0).getCell(col), new STBorder.Enum[] {STBorder.NIL, STBorder.THICK, STBorder.NIL, STBorder.NIL}); 
  }

  for (int col = 0; col < 3; col++) {
   setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[] {STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK}); 
  } 
  setCellBorders(table.getRow(1).getCell(3), new STBorder.Enum[] {STBorder.NIL, STBorder.NIL, STBorder.THICK, STBorder.THICK}); 
  setCellBorders(table.getRow(1).getCell(4), new STBorder.Enum[] {STBorder.THICK, STBorder.NIL, STBorder.NIL, STBorder.THICK}); 
  for (int col = 5; col < 8; col++) {
   setCellBorders(table.getRow(1).getCell(col), new STBorder.Enum[] {STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.THICK}); 
  }

  for (int col = 0; col < 8; col++) {
   setCellBorders(table.getRow(2).getCell(col), new STBorder.Enum[] {STBorder.NIL, STBorder.NIL, STBorder.NIL, STBorder.NIL}); 
  }

  table.getRow(0).setHeight(28*20); // 28pt row height
  table.getRow(0).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);

  XWPFTableCell cell = table.getRow(0).getCell(0);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.setBold(true);
  run.setText("Species:");

  cell = table.getRow(0).getCell(2);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  paragraph.setAlignment(ParagraphAlignment.RIGHT);
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.setBold(true);
  run.setText("Greater silver smelt");

  cell = table.getRow(0).getCell(4);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.setBold(true);
  run.setText("Zone:");

  cell = table.getRow(0).getCell(6);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.setBold(true);
  run.setText("Union and international waters of 1 and 2");

  table.getRow(1).setHeight(28*20); // 28pt row height
  table.getRow(1).getCtRow().getTrPr().getTrHeightArray(0).setHRule(STHeightRule.EXACT);

  cell = table.getRow(1).getCell(2);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  paragraph.setAlignment(ParagraphAlignment.RIGHT);
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.addBreak();
  run = paragraph.createRun();
  run.setItalic(true);
  run.setText("Argentinia silos");

  cell = table.getRow(1).getCell(6);
  paragraph = (cell.getParagraphs().size() > 0)?cell.getParagraphs().get(0):cell.addParagraph();
  paragraph.setIndentationLeft(5*20); // 10pt left indentation
  run = (paragraph.getRuns().size() > 0)?paragraph.getRuns().get(0):paragraph.createRun();
  run.addTab();
  run = paragraph.createRun();
  run.addTab();
  run = paragraph.createRun();
  run.setText("(2)");
  run.addBreak();
  run = paragraph.createRun();
  run.setText("(ARU/1/2)");

  paragraph = document.createParagraph();

  CTSectPr sectPr = document.getDocument().getBody().getSectPr();
  if (sectPr == null) sectPr = document.getDocument().getBody().addNewSectPr();
  CTPageSz pageSz = sectPr.addNewPgSz();
  pageSz.setOrient(STPageOrientation.LANDSCAPE);
  pageSz.setH(BigInteger.valueOf(12240)); //12240 Twips = 12240/20 = 612 pt = 612/72 = 8.5"
  pageSz.setW(BigInteger.valueOf(15840)); //15840 Twips = 15840/20 = 792 pt = 792/72 = 11"

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

 }
}

Результат:

enter image description here

...