Java導出帶格式的Excel數據到Word表格

前言

在Word中創建報告時,我們經常會遇到這樣的情況:我們需要將數據從Excel中複製和粘貼到Word中,這樣讀者就可以直接在Word中瀏覽數據,而不用打開Excel文檔。在本文中,您將學習如何使用Spire.Office for Java將Excel數據轉換為Word表格並保留格式。


程序環境

安裝Spire.Office for Java

首先,你需要在你的Java程序中添加Spire.Office.jar文件作為一個依賴項。該JAR文件可以從這個鏈接下載。如果你使用Maven,你可以通過在項目的pom.xml文件中添加以下代碼,在你的應用程序中輕鬆導入該JAR文件。

點擊查看代碼
<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url> //repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.office</artifactId>
        <version>7.9.6</version>
    </dependency>
</dependencies>

小tips:請注意版本號的變化

將帶格式的Excel數據導出到Word表格

步驟

創建一個Workbook對象,並使用Workbook.loadFromFile()方法加載一個Excel樣本文件。
• 使用Workbook.getWorksheets().get()方法獲取一個特定的工作表。
• 創建一個Document對象,並向其添加一個章節。
• 使用Section.addTable()方法添加一個表格。
• 檢測工作表中的合併單元格,並使用自定義方法mergeCells()合併Word tale中的相應單元格。
• 使用CellRange.getValue() 方法獲取特定Excel單元格的值,並使用TableCell.addParagraph().appendText()方法將其添加到Word表中的一個單元格。
• 使用自定義方法copyStyle()將字體樣式和單元格樣式從Excel複製到Word表格中。
• 使用Document.saveToFile()方法將文檔保存到Word文件中。

代碼示例

點擊查看代碼
import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.PageOrientation;
import com.spire.doc.documents.VerticalAlignment;
import com.spire.doc.fields.TextRange;
import com.spire.xls.*;

public class ExportExcelToWord {

    public static void main(String[] args) {

        //下載一個Excel文件
        Workbook workbook = new Workbook();
        workbook.loadFromFile("C:/Users/Administrator/Desktop/sample.xlsx");

        //得到第一張工作表
        Worksheet sheet = workbook.getWorksheets().get(0);

        //創建一個Word文檔
        Document doc = new Document();
        Section section = doc.addSection();
        section.getPageSetup().setOrientation(PageOrientation.Landscape);

        //添加一個表格
        Table table = section.addTable(true);
        table.resetCells(sheet.getLastRow(), sheet.getLastColumn());

        //合併單元格
        mergeCells(sheet, table);

        for (int r = 1; r <= sheet.getLastRow(); r++) {

            //設置行高
            table.getRows().get(r - 1).setHeight((float) sheet.getRowHeight(r));

            for (int c = 1; c <= sheet.getLastColumn(); c++) {
                CellRange xCell = sheet.getCellRange(r, c);
                TableCell wCell = table.get(r - 1, c - 1);

                //獲得特定Excel單元格的值並將其添加到Word表格單元格
                TextRange textRange = wCell.addParagraph().appendText(xCell.getValue());

                // 從Excel複製字體和單元格樣式到Word
                copyStyle(textRange, xCell, wCell);
            }
        }

        //Save the document to a Word file保存文檔為Word文件
        doc.saveToFile("ExportToWord.docx", FileFormat.Docx);
    }

    //如果有合併的區域,則合併單元格
    private static void mergeCells(Worksheet sheet, Table table) {
        if (sheet.hasMergedCells()) {

            //從Excel中獲取合併的單元格範圍
            CellRange[] ranges = sheet.getMergedCells();
            for (int i = 0; i < ranges.length; i++) {
                int startRow = ranges[i].getRow();
                int startColumn = ranges[i].getColumn();
                int rowCount = ranges[i].getRowCount();
                int columnCount = ranges[i].getColumnCount();

                //合併Word表格中的對應單元格
                if (rowCount > 1 && columnCount > 1) {
                    for (int j = startRow; j <= startRow + rowCount ; j++) {
                        table.applyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                    }
                    table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1 );
                }
                if (rowCount > 1 && columnCount == 1 ) {
                     table.applyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount - 1);
                }
                if (columnCount > 1 && rowCount == 1 ) {
                    table.applyHorizontalMerge(startRow - 1, startColumn - 1,  startColumn - 1 + columnCount-1);
                }
            }
        }
    }

    //複製Excel單元格樣式到Word表格
    private static void copyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell) {

        //複製字體樣式
        wTextRange.getCharacterFormat().setTextColor(xCell.getStyle().getFont().getColor());
        wTextRange.getCharacterFormat().setFontSize((float) xCell.getStyle().getFont().getSize());
        wTextRange.getCharacterFormat().setFontName(xCell.getStyle().getFont().getFontName());
        wTextRange.getCharacterFormat().setBold(xCell.getStyle().getFont().isBold());
        wTextRange.getCharacterFormat().setItalic(xCell.getStyle().getFont().isItalic());

        //複製背景色
        wCell.getCellFormat().setBackColor(xCell.getStyle().getColor());

        //複製水平對齊方式
        switch (xCell.getHorizontalAlignment()) {
            case Left:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Left);
                break;
            case Center:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
                break;
            case Right:
                wTextRange.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Right);
                break;
        }
        
        //複製垂直對齊方式
        switch (xCell.getVerticalAlignment()) {
            case Bottom:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Bottom);
                break;
            case Center:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
                break;
            case Top:
                wCell.getCellFormat().setVerticalAlignment(VerticalAlignment.Top);
                break;
        }
    }
}

效果圖

image

—THE END—