You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Angular运行时编辑Word(.docx)文档

在Angular中显示并编辑Word(.docx)文件(保留格式+运行时更新)

一、正确显示带格式的Docx内容

直接读取docx文件为UTF-8文本无效,因为docx本质是包含XML结构的ZIP压缩包。推荐用mammoth.js库解析docx为带格式的HTML,步骤如下:

  1. 安装依赖
npm install mammoth --save
  1. 组件中实现解析逻辑
    通过文件选择器读取docx文件,调用mammoth解析为HTML:
import * as mammoth from 'mammoth';

export class DocxViewerComponent {
  displayedHtml: string = '';

  handleFileInput(event: Event) {
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const arrayBuffer = e.target?.result as ArrayBuffer;
      mammoth.convertToHtml({arrayBuffer: arrayBuffer})
        .then(result => {
          this.displayedHtml = result.value; // 带格式的HTML内容
          // result.messages 包含解析警告,可按需处理
        })
        .catch(err => console.error('解析失败:', err));
    };
    reader.readAsArrayBuffer(file);
  }
}
  1. 模板渲染与样式适配
    用innerHTML绑定解析后的HTML,添加基础CSS还原Word格式:
<input type="file" accept=".docx" (change)="handleFileInput($event)">
<div class="docx-content" [innerHTML]="displayedHtml"></div>
.docx-content h1, .docx-content h2 {
  font-weight: bold;
  margin: 1em 0;
}
.docx-content p {
  margin: 0.5em 0;
  line-height: 1.5;
}
.docx-content ul, .docx-content ol {
  margin-left: 1.5em;
}

二、实现编辑功能与运行时更新

结合富文本编辑器,将解析后的HTML导入编辑器,实现实时编辑与内容更新:

方案1:Angular Material Editor(轻量集成)

  1. 安装依赖
npm install @angular/material @angular/cdk @angular/forms
  1. 配置模块
    在app.module.ts中导入相关模块:
import { MatEditorModule } from '@angular/material/editor';
import { FormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // 其他模块
    MatEditorModule,
    FormsModule
  ]
})
export class AppModule {}
  1. 组件绑定与实时预览
export class DocxEditorComponent {
  editorContent: string = '';

  handleFileInput(event: Event) {
    // 同解析逻辑,将result.value赋值给this.editorContent
    const file = (event.target as HTMLInputElement).files?.[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (e) => {
      const arrayBuffer = e.target?.result as ArrayBuffer;
      mammoth.convertToHtml({arrayBuffer: arrayBuffer})
        .then(result => {
          this.editorContent = result.value;
        })
        .catch(err => console.error('解析失败:', err));
    };
    reader.readAsArrayBuffer(file);
  }
}

模板代码:

<input type="file" accept=".docx" (change)="handleFileInput($event)">
<mat-editor [(ngModel)]="editorContent" style="height: 500px;"></mat-editor>
<div class="preview" [innerHTML]="editorContent"></div>

方案2:Quill.js(灵活富文本编辑)

  1. 安装依赖
npm install quill ngx-quill --save
  1. 导入模块
import { QuillModule } from 'ngx-quill';

@NgModule({
  imports: [QuillModule.forRoot()]
})
export class AppModule {}
  1. 组件实现
import { Component } from '@angular/core';
import * as mammoth from 'mammoth';

@Component({
  selector: 'app-docx-editor',
  template: `
    <input type="file" accept=".docx" (change)="handleFileInput($event)">
    <quill-editor [(ngModel)]="editorContent" (onContentChanged)="onContentUpdated()"></quill-editor>
    <div class="preview" [innerHTML]="editorContent"></div>
  `
})
export class DocxEditorComponent {
  editorContent: string = '';

  handleFileInput(event: Event) {
    // 同解析逻辑,赋值给this.editorContent
  }

  onContentUpdated() {
    // 内容更新时的自定义逻辑,比如自动保存
    console.log('内容已更新');
  }
}

三、将编辑内容保存为Docx

用docxtemplater结合pizzip实现HTML转docx:

  1. 安装依赖
npm install docxtemplater pizzip --save
  1. 保存逻辑实现
import * as Docxtemplater from 'docxtemplater';
import * as PizZip from 'pizzip';

export class DocxEditorComponent {
  // 其他代码

  saveAsDocx() {
    // 加载提前放在assets的空白docx模板
    fetch('assets/blank.docx')
      .then(res => res.arrayBuffer())
      .then(buffer => {
        const zip = new PizZip(buffer);
        const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });
        
        // 提取编辑内容的文本(如需保留完整格式,可使用html-docx-js库直接转换HTML)
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = this.editorContent;
        const textContent = tempDiv.textContent || '';

        doc.setData({ content: textContent });
        doc.render();

        const out = doc.getZip().generate({ type: 'blob' });
        // 触发下载
        const url = URL.createObjectURL(out);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'edited-document.docx';
        a.click();
        URL.revokeObjectURL(url);
      });
  }
}

内容的提问来源于stack exchange,提问作者Prashant

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 06:35:31