1. 程式人生 > >Java 操作Word表格——建立巢狀表格、新增/複製表格行或列、設定表格是否禁止跨頁斷行

Java 操作Word表格——建立巢狀表格、新增/複製表格行或列、設定表格是否禁止跨頁斷行

本文將對如何在Java程式中操作Word表格作進一步介紹。操作要點包括

  • 如何在Word中建立巢狀表格、
  • 對已有表格新增行或者列
  • 複製已有表格中的指定行或者列
  • 對跨頁的表格可設定是否禁止跨頁斷行

 建立表格,包括新增資料、插入表格、合併單元格、設定表格樣式、單元格居中、單元格背景色,單元格字型樣式等設定,可參考這篇文章裡的內容。


 

使用工具:Free Spire.Doc for Java (免費版)

Jar檔案可通過官網下載jar檔案包,下載後,解壓檔案,將lib資料夾下的Spire.Doc.jar匯入Java程式;也可以在maven專案中通過maven倉庫安裝匯入。


 

【新增Word巢狀表格】

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


public class NestedTable {
    public static void main(String[]args){
        //載入測試文件
        Document doc = new Document("sample.docx");
        
        //獲取指定表格中的單元格,並設定行高、列寬
Section sec = doc.getSections().get(0);
        Table table = sec.getTables().get(0);
        table.getRows().get(0).setHeight(120f);
        table.getRows().get(0).getCells().get(0).setWidth(380);

        //新增巢狀表格到指定單元格
        Table nestedtable = table.get(0,0).addTable(true);
        nestedtable.getTableFormat().setHorizontalAlignment(RowAlignment.Center);//設定巢狀表格在單元格中的對齊方式
        nestedtable.resetCells(4,4);//指定巢狀表格行數、列數
        nestedtable.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);//設定巢狀表格內容自適應方法
        //宣告表格陣列內容
        String[][] data ={
                new String[]{"編號","產區","最新型號","生產日期",},
                new String[]{"1","A","V2.2.0","2019-06-21"},
                new String[]{"2","B","V2.6.1","2019-06-18"},
                new String[]{"3","C","V2.6.2","2019-06-14"},
        };

        //填充陣列內容到巢狀表格
        for (int i = 0; i < data.length; i++) {
            TableRow dataRow = nestedtable.getRows().get(i);
            dataRow.getCells().get(i).setWidth(160);
            dataRow.setHeight(25);
            dataRow.setHeightType(TableRowHeightType.Exactly);
            for (int j = 0; j < data[i].length; j++) {
                dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]);
                range.getCharacterFormat().setFontName("楷體");
                range.getCharacterFormat().setFontSize(11f);
                range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            }
        }

        //儲存文件
        doc.saveToFile("nesedtable1.docx",FileFormat.Docx_2010);
    }
}

巢狀表格效果:

 

【在Word表格中新增行或者列】

     1. 新增行

import com.spire.doc.*;

public class AddRow {
    public static void main(String[] args){
        //載入測試文件
        Document doc = new Document();
        doc.loadFromFile("sample.docx");

        //獲取表格
        Section section = doc.getSections().get(0);
        Table table = section.getTables().get(0);

        table.addRow();//預設在表格最下方插入一行
        //table.getRows().insert(2,table.addRow());//在表格中第3行插入一行
        //table.addRow(4);//預設在表格最下方新增4個單元格
        //table.addRow(true,2);//帶格式在最後一行新增2個單元格
        //table.addRow(false,2);//不帶格式在最後一行新增2個單元格

        //儲存文件
        doc.saveToFile("addrow.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格行新增效果:

     2. 新增列

import com.spire.doc.*;
import com.spire.doc.documents.BorderStyle;

import java.awt.*;

public class AddColumn {
    public static void main(String[] args){
        //載入測試文件
        Document doc = new Document();
        doc.loadFromFile("sample.docx");

        //獲取表格
        Section section = doc.getSections().get(0);
        Table table = section.getTables().get(0);

//獲取表格單元格寬度及型別
        float width = table.get(0,0).getWidth();
        CellWidthType type = table.get(0,0).getCellWidthType();
        //遍歷表格每一行
        for (int i = 0; i < table.getRows().getCount(); i++) {
            TableRow row = table.getRows().get(i);//獲取表格每一行
            Color color = row.getCells().get(0).getCellFormat().getBackColor();//獲取表格單元格背景色
            //基於表格每行,在最後新增一個單元格,並設定單元格格式
            TableCell cell = row.addCell(true);//預設在最後一列新增單元格
            cell.setWidth(width);
            cell.setCellWidthType(type);
            cell.getCellFormat().getBorders().setBorderType(BorderStyle.Single);
            cell.getCellFormat().setBackColor(color);
            //如需在指定位置插入列,基於以上程式碼並增加下面一行程式碼即可
            //row.getCells().insert(2,cell);//插入一列作為第三列
        }

        //儲存文件
        doc.saveToFile("addcolumn.docx", FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格列新增效果:

 

【複製Word表格中的行或者列】

    1. 複製行

import com.spire.doc.*;

public class CopyRow {
    public static void main(String[] args) {
        //載入測試文件
        Document doc = new Document();
        doc.loadFromFile("test.docx");

        //獲取表格
        Section section = doc.getSections().get(0);
        Table table =section.getTables().get(0);

        //複製第三行,並將複製後的行插入到表格作為第五行
        TableRow row = table.getRows().get(2).deepClone();
        table.getRows().insert(4,row);

        //儲存文件
        doc.saveToFile("CopyRow.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格行復制效果:

      2. 複製列

import com.spire.doc.*;

public class CopyColumn {
    public static void main(String[] args) {
       //載入測試文件
        Document doc = new Document();
        doc.loadFromFile("test.docx");

        //獲取表格
        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);
            TableCell cell = (TableCell) row.getCells().getLastItem().deepClone();
            //row.getCells().add(cell);//預設在每行最後新增複製後的單元格
            row.getCells().insert(2,cell);//在指定位置插入複製後的單元格
        }

        //儲存文件
        doc.saveToFile("CopyColumn1.docx",FileFormat.Docx_2013);
        doc.dispose();
    }
}

表格列複製效果:

 

【設定Word表格是否禁止跨頁斷行】

這裡通過兩種方式來設定防止表格跨頁出現斷行的效果,供參考。

  1. 設定屬性禁止跨頁斷行

import com.spire.doc.*;

public class PreventPagebreak {
    public static void main(String[]args){
        //載入測試文件
        Document doc= new Document("test.docx");

        //獲取表格
        Table table = doc.getSections().get(0).getTables().get(0);

        //設定表格是否分頁斷行
        table.getTableFormat().isBreakAcrossPages(false);

        //儲存文件
        doc.saveToFile("result.docx",FileFormat.Docx_2013);
    }
}

    2. 保持表格內容在同一頁面

import com.spire.doc.*;
import com.spire.doc.documents.Paragraph;

public class PreventPagebreak {
    public static void main(String[]args){
        //載入測試文件
        Document doc= new Document("test.docx");

        //獲取表格
        Table table = doc.getSections().get(0).getTables().get(0);

        //遍歷表格單元格
        for (int i = 0;i< table.getRows().getCount();i++) {
            TableRow rows = table.getRows().get(i);
            for (int j = 0; j< rows.getCells().getCount(); j++){
                for (int z= 0; z < rows.getCells().get(j).getParagraphs().getCount();z++){
                    Paragraph p = rows.getCells().get(j).getParagraphs().get(z);
                    p.getFormat().setKeepFollow(true);//設定表格內容在同一頁顯示
                }
            }
        }

        //儲存文件
        doc.saveToFile("result1.docx",FileFormat.Docx_2013);
    }
}

 

(本文完)

轉載請註明出處