在 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>https://repo.e-iceblue.cn/repository/maven-public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.office</artifactId>
        <version>10.10.0</version>
    </dependency>
</dependencies>
将带格式的 Excel 数据导出到 Word 表格
以下是使用 Spire.Office for Java 将 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 文件中。
- Java
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);
            }
        }
        //保存文档为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;
        }
    }
}
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
 



 
					



