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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15149422/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:38:46  来源:igfitidea点击:

How to auto fit table and aligning the table to center, according to Word Document Size Apache-POI?

javaapache-poixwpf

提问by Rand Mate

How to make this table to auto-fit to document page width, when the column size increases, using apache-poi and aligning that table to center.

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

This code generates a word Document extracting data from Java to word file located in c drive. I have manually set width but it now works fine. If would be valuable for me if proper guidance is provided

此代码生成一个 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 
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);
9
CTJc jc = pr.addNewJc();        
jc.setVal(STJc.RIGHT);
pr.setJc(jc);
9
  XWPFTable table = doc.createTable(nRows, nCols);
  table.getCTTbl().addNewTblPr().addNewTblW().setW(BigInteger.valueOf(10000));
9 Value \t\t\t\t Normal Ranges33"); 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(); }

}

}

回答by Mohammed Nafie

to set the table to auto fit , basically it's just extending the width to a specific size. example

将表格设置为 auto fit ,基本上它只是将宽度扩展到特定大小。例子

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

as for aligning the table to the center

至于将桌子对齐到中心

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

回答by user2940073

To set the width of a table:

要设置表格的宽度:

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

To set column width:

设置列宽:

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

If data increases in cell it effects the width of column i.e column width also will increase so to avoid this kind of problems we need to check length of string value in cell and we need to add \n (new line) in string by doing this we can set width of column.

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

In my project i have struggled alot to set column width and i have solved this issue by controlling data in cell.

在我的项目中,我一直在努力设置列宽,我通过控制单元格中的数据解决了这个问题。

回答by Holger Herrmann

You can set the width of a table in percent of the actual page size. First, get the width of the page:

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

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

Second step, get the margins of the page and calculate the effective page size:

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

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"));
    }
}

Now, let's say you want the table to have a width of 60% of the effective page size. Then you calculate the size for your table. (If you want the table to fit to the actual page size, simply use 1.0):

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

##代码##

Finally, set this size to your table:

最后,将此大小设置为您的表格:

##代码##

Hope this helps!

希望这可以帮助!

Best, Holger

最好的,霍尔格

回答by BaiJiFeiLong

Just use "100%":

只需使用“100%”:

##代码##