vue实现word文档导出
使用docx.js库生成Word文档
安装docx.js库:
npm install docx
创建一个简单的Word文档并导出:
import { Document, Paragraph, TextRun, Packer } from "docx";
const doc = new Document({
sections: [{
children: [
new Paragraph({
children: [
new TextRun("Hello World"),
new TextRun({
text: "Foo Bar",
bold: true,
}),
],
}),
],
}],
});
Packer.toBlob(doc).then(blob => {
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = "example.docx";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
使用html-docx-js转换HTML为Word
安装html-docx-js库:
npm install html-docx-js
将HTML内容转换为Word文档:
import htmlDocx from "html-docx-js";
const html = `
<h1>标题</h1>
<p>这是一个段落</p>
<ul>
<li>项目1</li>
<li>项目2</li>
</ul>
`;
const converted = htmlDocx.asBlob(html);
const url = URL.createObjectURL(converted);
const link = document.createElement("a");
link.href = url;
link.download = "document.docx";
link.click();
使用file-saver保存文件
安装file-saver库简化下载过程:
npm install file-saver
结合docx.js使用:
import { saveAs } from "file-saver";
import { Packer } from "docx";
// ...创建doc对象后
Packer.toBlob(doc).then(blob => {
saveAs(blob, "document.docx");
});
后端生成Word文档
使用Node.js后端服务生成Word:
const express = require("express");
const { Document, Paragraph, Packer } = require("docx");
const app = express();
app.get("/export-word", (req, res) => {
const doc = new Document({
sections: [{
children: [
new Paragraph("后端生成的Word文档")
]
}]
});
Packer.toBuffer(doc).then(buffer => {
res.setHeader(
"Content-Type",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
);
res.setHeader("Content-Disposition", "attachment; filename=export.docx");
res.send(buffer);
});
});
app.listen(3000);
处理复杂格式和样式
创建带样式的复杂文档:
const doc = new Document({
sections: [{
properties: {
page: {
margin: {
top: 1000,
right: 1000,
bottom: 1000,
left: 1000,
}
}
},
children: [
new Paragraph({
heading: "Heading1",
children: [
new TextRun({
text: "带样式的标题",
bold: true,
size: 32,
font: "Arial"
})
]
}),
new Paragraph({
children: [
new TextRun({
text: "红色文本",
color: "FF0000",
italics: true
})
]
})
]
}]
});
使用模板替换内容
创建模板替换方案:
function generateDocument(data) {
return new Document({
sections: [{
children: [
new Paragraph(`姓名: ${data.name}`),
new Paragraph(`年龄: ${data.age}`),
new Paragraph({
text: `地址: ${data.address}`,
alignment: "left"
})
]
}]
});
}
// 使用示例
const userData = {
name: "张三",
age: 30,
address: "北京市朝阳区"
};
const doc = generateDocument(userData);
// 然后使用Packer导出...
这些方法提供了从简单到复杂的Vue中导出Word文档的解决方案,可以根据项目需求选择合适的方式。对于简单需求,纯前端方案足够;复杂需求可能需要结合后端服务。







