后端使用NPOI返回word文档文件流前端将其导出下载在浏览器
中打开
-
在后端使用NPOI生成需要导出的word文档,将其保存为字节数组。
-
在前端使用fetch或axios等工具向后端发送请求,获取生成的word文档文件流。
-
将获取到的文件流转换为Blob对象。
-
创建一个a标签,设置其href属性为转换后的Blob对象的URL,设置download属性为导出的文件名。
-
将a标签添加到DOM中,并模拟点击该标签,即可下载并打开生成的word文档。
示例代码:
后端代码:
using NPOI.XWPF.UserModel;
public byte[] ExportWordDocument()
{
XWPFDocument doc = new XWPFDocument();
// 创建并编辑word文档
// ...
// 将word文档保存为字节数组
using (MemoryStream stream = new MemoryStream())
{
doc.Write(stream);
return stream.ToArray();
}
}
前端代码:
fetch('/api/exportWordDocument', {
method: 'GET',
responseType: 'blob' // 指定响应类型为Blob
}).then(response => {
response.blob().then(blob => {
let a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = 'document.docx'; // 设置导出的文件名
a.style.display = 'none';
document.body.appendChild(a);
a.click(); // 模拟点击a标签
document.body.removeChild(a);
});
});
原文地址: https://www.cveoy.top/t/topic/7HK 著作权归作者所有。请勿转载和采集!