如何根据Word文档大小Apache-POI自动调整表格并将表格居中对齐?

问题描述 投票:0回答:5

当列大小增加时,如何使该表格自动适应文档页面宽度,使用 apache-poi 并将该表格居中对齐。

此代码生成一个word文档,将Java中的数据提取到位于c盘的word文件中。我已经手动设置宽度,但现在工作正常。如果提供适当的指导对我来说是有价值的

public Word2Doc() throws Exception {

    System.out.println("This is Word To Document Class");

    File file = null; 
           FileOutputStream fos = null; 
           XWPFDocument document = null; 
           XWPFParagraph para = null; 
           XWPFRun run = null; 
           try { 
               // Create the first paragraph and set it's text. 
               document = new XWPFDocument(); 
               para = document.createParagraph(); 

               para.setAlignment(ParagraphAlignment.CENTER); 

               para.setSpacingAfter(100); 

               para.setSpacingAfterLines(10);
               run = para.createRun(); 
               for(int i=1; i<=5; i++)
               run.setText("Test Name \009\009\009 Value \t\t\t\t Normal Ranges\013\013"); 
               run.addBreak();    // similar to new line
               run.addBreak();

               XWPFTable table = document.createTable(4, 3);

               table.setRowBandSize(1);
               table.setWidth(1);
               table.setColBandSize(1);
               table.setCellMargins(1, 1, 100, 30);

               table.setStyleID("finest");


               table.getRow(1).getCell(1).setText("EXAMPLE OF TABLE");
               table.getRow(2).getCell(1).setText("fine");
               XWPFParagraph p1 = table.getRow(0).getCell(0).getParagraphs().get(0);
               p1.setAlignment(ParagraphAlignment.CENTER);
                       XWPFRun r1 = p1.createRun();
                       r1.setBold(true);
                       r1.setText("Test Name");
                       r1.setItalic(true);
                       r1.setFontFamily("Courier");
                       r1.setUnderline(UnderlinePatterns.DOT_DOT_DASH);
                       r1.setTextPosition(100);

              //Locating the cell values
                        table.getRow(0).getCell(1).setText("Value"); 
                        table.getRow(0).getCell(2).setText("Normal Ranges"); 

                       table.getRow(2).getCell(2).setText("numeric values");

                        table.setWidth(120);

               file = new File("c:\\nwhpe.docx"); 
               if(file.exists())
                   file.delete();


               FileOutputStream out = new FileOutputStream(file);
               document.write(out);
               out.close();
           } 

       } 
public static void main(String ar[]) throws Exception{
    new Word2Doc();
}

}

java apache-poi xwpf
5个回答
12
投票

将表格设置为自动调整,基本上只是将宽度扩展到特定尺寸。 例子

CTTbl table        = poiTable.getCTTbl();
CTTblPr pr         = table.getTblPr();
CTTblWidth  tblW = pr.getTblW();
tblW.setW(BigInteger.valueOf(5000));
tblW.setType(STTblWidth.PCT);
pr.setTblW(tblW);
table.setTblPr(pr);

至于将桌子对齐中心

CTJc jc = pr.addNewJc();        
jc.setVal(STJc.RIGHT);
pr.setJc(jc);

7
投票

只需使用“100%”:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019-08-21 13:49
 */
public class WordDemo {

    @SneakyThrows
    public static void main(String[] args) {
        XWPFDocument document = new XWPFDocument();
        XWPFTable table = document.createTable(3, 4);
        table.setWidth("100%");
        for (int i = 0; i < 3; ++i) {
            for (int j = 0; j < 4; ++j) {
                table.getRow(i).getCell(j).setText(String.format("%d:%d", i + i, j + 1));
            }
        }
        document.write(new FileOutputStream("hello.docx"));
    }
}

4
投票

设置表格宽度:

  XWPFTable table = doc.createTable(nRows, nCols);
  table.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(10000));

设置列宽:

cell.getCTTc().addNewTcPr().addNewTcW().setW(BigInteger.valueOf(2000));

如果单元格中的数据增加,它会影响列的宽度,即列宽也会增加,因此为了避免此类问题,我们需要检查单元格中字符串值的长度,并且需要添加 (换行)在字符串中通过这样做我们可以设置列的宽度。

在我的项目中,我在设置列宽方面付出了很多努力,我通过控制单元格中的数据解决了这个问题。


3
投票

您可以按实际页面大小的百分比设置表格的宽度。 首先,获取页面的宽度:

CTSectPr sectPr = document.getDocument().getBody().getSectPr();
CTPageSz pageSize = sectPr.getPgSz();
double pageWidth = pageSize.getW().doubleValue();

第二步,获取页面边距并计算有效页面尺寸:

CTPageMar pageMargin = sectPr.getPgMar();
double pageMarginLeft = pageMargin.getLeft().doubleValue();
double pageMarginRight = pageMargin.getRight().doubleValue();
double effectivePageWidth = pageWidth - pageMarginLeft - pageMarginRight;

现在,假设您希望表格的宽度为有效页面大小的 60%。然后计算桌子的尺寸。 (如果你想让表格适合实际页面大小,只需使用1.0):

double widthInPercent = 0.6;
int size = (int) (effectivePageWidth * widthInPercent);

最后,将此尺寸设置为您的桌子:

CTTblWidth width = table.getCTTbl().addNewTblPr().addNewTblW();
width.setType(STTblWidth.DXA);
width.setW(new BigInteger(size + ""));

希望这有帮助!

最好的, 霍尔格


0
投票

对我来说,解决方案是取消设置所有先前设置的宽度并将表格布局类型重置为自动调整:

CTTbl ctTbl = table.getCTTbl();

CTTblGrid ctTblGrid = ctTbl.getTblGrid();
ctTblGrid.getGridColList().forEach(CTTblGridCol::unsetW);

CTTblLayoutType type = ctTbl.getTblPr().addNewTblLayout();
type.setType(STTblLayoutType.AUTOFIT);

但是我处理从 html 转换而来的 docx。

© www.soinside.com 2019 - 2024. All rights reserved.