乐于分享
好东西不私藏

Word文档的上传、编辑、清空&保存

Word文档的上传、编辑、清空&保存

效果图
下载–html
npm install mammoth quill file-saver
<!-- 操作按钮区 --><divclass="action-buttons">  <el-upload    class="upload-document"    action=""    :auto-upload="false"    :on-change="handleFileUpload"    accept=".docx"  >    <el-buttontype="primary">      <el-icon><Upload /></el-icon> 上传Word文档    </el-button>  </el-upload>  <el-buttontype="success" @click="saveDocument">    <el-icon><Download /></el-icon> 保存文档  </el-button>  <el-buttontype="info" @click="clearContent">    <el-icon><Delete /></el-icon> 清空内容  </el-button></div><!-- 编辑器区域 --><divclass="editor-container">  <divid="editor"ref="editorRef"></div></div>
import * as mammoth from 'mammoth';import Quill from 'quill';import 'quill/dist/quill.snow.css';import { saveAs } from 'file-saver';// 编辑器实例const editorRef = ref(null);let quill = null;// 初始化编辑器const initEditor = () => {  quill = new Quill('#editor', {    theme'snow',    modules: {      toolbar: [        ['bold''italic''underline''strike'],        ['blockquote''code-block'],        [{ 'header'1 }, { 'header'2 }],        [{ 'list''ordered' }, { 'list''bullet' }],        [{ 'script''sub' }, { 'script''super' }],        [{ 'indent''-1' }, { 'indent''+1' }],        [{ 'direction''rtl' }],        [{ 'size': ['small'false'large''huge'] }],        [{ 'header': [123456false] }],        [{ 'color': [] }, { 'background': [] }],        [{ 'font': [] }],        [{ 'align': [] }],        ['clean']      ]    },    placeholder'请输入内容或上传Word文档...'  });  // 监听内容变化  quill.on('text-change'function() {    console.log('内容已更改');  });};// 处理文件上传const handleFileUpload = async (file) => {  try {    message.value = '正在解析文档...';    messageType.value = 'info';    const result = await mammoth.convertToHtml({ arrayBuffer: file.raw.arrayBuffer() });    quill.root.innerHTML = result.value;    message.value = '文档解析成功';    messageType.value = 'success';  } catch (error) {    console.error('解析文档失败:', error);    message.value = '文档解析失败: ' + error.message;    messageType.value = 'error';  }};// 保存文档const saveDocument = () => {  try {    const htmlContent = quill.root.innerHTML;    const blob = new Blob([htmlContent], { type'text/html;charset=utf-8' });    saveAs(blob, 'document.html');    message.value = '文档保存成功';    messageType.value = 'success';  } catch (error) {    console.error('保存文档失败:', error);    message.value = '文档保存失败: ' + error.message;    messageType.value = 'error';  }};// 清空内容const clearContent = () => {  quill.setText('');  message.value = '内容已清空';  messageType.value = 'info';};// 组件挂载时初始化onMounted(() => {  initEditor();});// 组件卸载时清理onUnmounted(() => {  if (quill) {    // 清理编辑器实例    quill = null;  }});

代码解释

mammoth.convertToHtml
将.docx文件转换为HTML格式以便在网页中展示。Mammoth.js是一个高效的JavaScript库,专门用于处理这种转换任务。
  • 引入库
    使用import mammoth from "mammoth"引入Mammoth.js库。
  • 转换文件
    定义convertDocxToHtml函数,接受文件对象作为参数,将文件转换为ArrayBuffer后调用mammoth.convertToHtml方法。
  • 处理结果
    在转换成功后,将生成的HTML内容插入到页面的指定元素中。

注意事项

1.格式兼容性
由于不同编辑器的格式处理方式不同,部分复杂格式可能无法完全还原。
2.文件大小
建议上传的Word文档大小不超过10MB,过大的文件可能会导致解析速度变慢。
3.图片处理
文档中的图片会被转换为base64格式嵌入到HTML中,可能会增加文件大小。
4.特殊格式
复杂的表格、图表、公式等可能无法完全正确解析和显示。
5.浏览器兼容性
建议使用Chrome、Firefox等现代浏览器以获得最佳体验。
6.性能优化
对于大文件,考虑使用Web Worker避免阻塞主线程,提升用户体验。