您的位置 首页 java

Java 创建、删除Word表格

在Word文档中,我们可以通过添加表格的方式来帮助我们更加清晰、直观地分析和展示数据。本文将介绍如何使用Free Spire.Doc for Java组件来给Word文档创建表格,及删除文档中已有的表格和表格内容。

添加产品及其依赖

方式 1: 通过E-iceblue中文官网下载组件,解压后将lib文件夹下的Spire.Doc.jar手动导入IDEA中。具体导入步骤参见下图。

方式 2: 通过Maven仓库安装产品及相关依赖。在pom.xml文件中配置Maven仓库路径,及指定Free Spire.Doc for Java的Maven依赖。

 <repositories>
        <repository>
            <id>com.e-iceblue</id>
            <url>
        </repository>
    </repositories>
<dependencies>
    <dependency>
        <groupId> e-iceblue </groupId>
        <artifactId>spire.doc.free</artifactId>
        <version>2.7.3</version>
    </dependency>
</dependencies>  

配置完成后,在IDEA中,您只需点击”Import Changes”即可导入JAR包;在Eclipse中,则需点击”Save”按钮。

代码示例

创建表格

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

public class CreateTable {
    public static void main(String[] args) {
        //创建Word文档
        Document document = new Document();
        //添加一个section
        Section section = document.addSection();

        //数据
        String[] header = {"Name", "Capital", "Continent", "Area"};
        String[][] data =
                {
                        new String[]{"Indonesia", "Jakarta", "Southeast Asia", "1913579"},
                        new String[]{"Bangladesh", "Dhaka", "South Asia", "147570"},
                        new String[]{"Mexican", "Mexico City", "North America", "1964375"},
                        new String[]{"Kenya", "Nairobi", "East Africa", "582646"},
                        new String[]{"China", "Beijing", "East Asia", "9600000"},
                };

        //添加表格
        Table table = section.addTable(true);
        //设置表格的行数和列数
        table.resetCells(data.length + 1, header.length);

        //设置第一行作为表格的表头并添加数据
        TableRow row = table.getRows().get(0);
        row.isHeader(true);
        row.setHeight(20);
        row.setHeightType(TableRowHeightType.Exactly);
        row.getRowFormat().setBackColor(Color.gray);
        for (int i = 0; i < header.length; i++) {
            row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
            Paragraph p = row.getCells().get(i).addParagraph();
            p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            TextRange range1 = p.appendText(header[i]);
            range1.getCharacterFormat().setFontName("Arial");
            range1.getCharacterFormat().setFontSize(12f);
            range1.getCharacterFormat().setBold(true);
        }

        //添加数据到剩余行
        for (int r = 0; r < data.length; r++) {
            TableRow dataRow = table.getRows().get(r + 1);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            dataRow.getRowFormat().setBackColor(Color.white);
            for (int c = 0; c < data[r].length; c++) {
                dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
                range2.getCharacterFormat().setFontName("Arial");
                range2.getCharacterFormat().setFontSize(10f);
            }
        }

        //设置单元格背景颜色
        for (int j = 1; j < table.getRows().getCount(); j++) {
            if (j % 2 == 0) {
                TableRow row2 = table.getRows().get(j);
                for (int f = 0; f < row2.getCells().getCount(); f++) {
                    row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
                }
            }
        }

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

创建效果:

删除表格

  • 删除整个表格
 import com.spire.doc.*;
import com.spire.doc.interfaces.ITable;
public class DeleteTable1 {
    public static void main(String[] args) {
        //创建实例
        Document doc = new Document();
        //加载Word文档
        doc.loadFromFile("C:\Users\Test1\Desktop\CreateTable.docx");

        //获取Section
        Section section = doc.getSections().get(0);

        //获取表格
        ITable table = section.getTables().get(0);

        //删除表格
        section.getTables().remove(table);

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

删除效果:

  • 仅删除表格中的内容
 import com.spire.doc.*;
public class DeleteTable2 {
    public static void main(String[] args) {
        //创建实例,加载测试文档
        Document doc = new Document();
        doc.loadFromFile("C:\Users\Test1\Desktop\CreateTable.docx");

        //获取Section
        Section section = doc.getSections().get(0);

        //获取表格
        Table table =section.getTables().get(0);
        //遍历表格每行
        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);
                cell.getChildObjects().clear();//清除所有子对象
                //cell.getCellFormat().clearFormatting();//清除单元格格式
                //cell.getParagraphs().removeAt(0);//删除单元格中的段落
            }
        }
        //保存文档
        doc.saveToFile("output/DeleteContent.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}  

删除效果:

(本文完)

文章来源:智云一二三科技

文章标题:Java 创建、删除Word表格

文章地址:https://www.zhihuclub.com/175156.shtml

关于作者: 智云科技

热门文章

网站地图