玖叶教程网

前端编程开发入门

添加表格到Word文本框及获取和删除文本框中的表格

前言

此篇教程将讲解如何添加表格到Word文本框及怎样获取、删除文本框中已有的表格。Free Spire.Doc for Java是此次代码演示所用到的控件。它是一款免费、专业的Java Word组件,开发人员使用它可以轻松地在Java应用程序中创建、编辑、读取、转换和打印Word文档。同时,作为一款完全独立的组件,其运行环境无需安装Microsoft Office。

测试环境

在运行代码前,需将Free Spire.Doc for Java产品包中的Spire.Doc.jar导入IDEA。导入方式有两种:其一,在IDEA中创建一个Maven项目,然后在pom.xml文件里键入以下代码,最后点击“Import Changes”即可;

<repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>http://repo.e-iceblue.cn/repository/maven-public/</url>
        </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>3.9.0</version>
    </dependency>
</dependencies>

其二,在E-iceblue中文官网上下载产品包,解压后将lib文件夹下的Spire.Doc.jar手动导入IDEA。

代码示例

示例1 添加表格到Word文本框

在添加表格到文本框时,Free Spire.Doc for Java支持设置表格大小,位置及操作表格样式,如合并单元格、设置表格背景色、表格字体大小及颜色等。

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.TextBox;
import com.spire.doc.fields.TextRange;
import java.awt.*;

public class AddTable {
    public static void main(String[] args) {
        //创建文档
        Document doc = new Document();
        //添加指定大小的文本框
        TextBox tb = doc.addSection().addParagraph().appendTextBox(380, 100);
        //设置文本框的相对位置
        tb.getFormat().setHorizontalOrigin(HorizontalOrigin.Left_Margin_Area);
        tb.getFormat().setHorizontalPosition(120f);
        tb.getFormat().setVerticalOrigin(VerticalOrigin.Page);
        tb.getFormat().setVerticalPosition(50f);
        //设置文本框边框样式
        tb.getFormat().setLineStyle(TextBoxLineStyle.Thin_Thick);
        tb.getFormat().setLineColor(Color.gray);

        //声明数组内容
        String[][] data = new String[][]{
                new String[]{"Country List"},
                new String[]{"Name", "Capital", "Continent", "Area"},
                new String[]{"China", "Beijing", "East Asia", "9600000"},
                new String[]{"Mexican", "Mexico City", "North America", "1964375"},
        };
        //添加表格
        Table table = tb.getBody().addTable();
        //指定表格行数、列数
        table.resetCells(4,4);
        //将数组内容填充到表格
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = table.getRows().get(i);
            dataRow.getCells().get(i).setWidth(70);
            dataRow.setHeight(22);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            for (int j = 0; j < data[i].length; j++) {
                dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range2 = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
                range2.getCharacterFormat().setFontName("Calibri");
                range2.getCharacterFormat().setFontSize(11f);
                range2.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                range2.getCharacterFormat().setBold(true);
            }
        }
       //设置指定行的背景色
        TableRow row = table.getRows().get(1);
        for (int z = 0; z < row.getCells().getCount(); z++) {
            row.getCells().get(z).getCellFormat().setBackColor(new Color(176,224,238));
        }
        //横向合并单元格
        table.applyHorizontalMerge(0,0,3);
        //应用表格样式
        table.applyStyle(DefaultTableStyle.Table_Grid_5);

        //保存文档
        doc.saveToFile("output/AddTabletoTextbox.docx", FileFormat.Docx_2013);
    }
}

添加效果:

示例2 获取文本框中的表格信息

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.io.*;

public class ReadTable {
    public static void main(String[] args) throws IOException {
        //加载示例文档
        Document doc = new Document();
        doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.docx");

        //获取第一个文本框
        TextBox textbox = doc.getTextBoxes().get(0);

        //获取文本框中第一个表格
        Table table = textbox.getBody().getTables().get(0);

        //保存文本
        String output = "output/readTableFromTextBox.txt";
        File file = new File(output);
        if (!file.exists()) {
            file.delete();
        }
        file.createNewFile();
        FileWriter fw = new FileWriter(file, true);
        BufferedWriter bw = new BufferedWriter(fw);

        //遍历表格中的段落并提取文本
        for (int i = 0; i < table.getRows().getCount(); i++) {
            TableRow row = table.getRows().get(i);
            for (int j = 0; j < row.getCells().getCount(); j++) {
                TableCell cell = row.getCells().get(j);
                for (int k = 0; k < cell.getParagraphs().getCount(); k++) {
                    Paragraph paragraph = cell.getParagraphs().get(k);
                    bw.write(paragraph.getText() + "\t");
                }
            }
            bw.write("\r\n");
        }

        bw.flush();
        bw.close();
        fw.close();
    }
}

效果图:

示例3 删除文本框中的表格

import com.spire.doc.*;
import com.spire.doc.fields.*;

public class DeleteTable {
    public static void main(String[] args) {
        //加载示例文档
        Document doc = new Document();
        doc.loadFromFile("C:\\Users\\Test1\\Desktop\\Test.docx");

        //获取第一个文本框
        TextBox textbox = doc.getTextBoxes().get(0);

        //获取文本框中第一个表格
        Table table = textbox.getBody().getTables().get(0);

        //删除第一个表格
        textbox.getBody().getTables().removeAt(0);

        //保存文档
        String output = "output/deleteTableFromTextBox.docx";
        doc.saveToFile(output, FileFormat.Docx_2013);
    }
}

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言