1. Aspose.Words:功能强大的Word处理器
安装Aspose.Words
shell
dotnet add package Aspose.Words
创建和下载Word文档
using Aspose.Words;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace WordDownloadApi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class WordFileController : ControllerBase
{
[HttpGet("download")]
public IActionResult DownloadWordFile()
{
// 创建一个新的文档
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// 添加内容
builder.Writeln("这是文章的标题");
builder.Writeln("这是第一个段落内容。");
// 将文档保存到内存流
using (MemoryStream memStream = new MemoryStream())
{
doc.Save(memStream, SaveFormat.Docx);
byte[] byteArray = memStream.ToArray();
string fileName = "sample_document.docx";
string mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
// 返回文件内容结果
return new FileContentResult(byteArray, mimeType)
{
FileDownloadName = fileName
};
}
}
}
}
2. IronWord:跨平台的Word文档处理库
安装IronWord
shell
dotnet add package IronWord
使用IronWord创建和下载Word文档
using IronWord;
using Microsoft.AspNetCore.Mvc;
using System.IO;
namespace IronWordController
{
[Route("api/[controller]")]
[ApiController]
public class IronWordController : ControllerBase
{
[HttpGet("download")]
public IActionResult DownloadDocument()
{
var document = new IronDocument();
document.AddParagraph("这是标题");
document.AddParagraph("这是正文内容。");
using (var stream = new MemoryStream())
{
document.SaveAs(stream, IronDocumentFormat.Docx);
stream.Position = 0;
return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "ironword_document.docx");
}
}
}
}
结论
往期精品推荐: