c# MVC 4:创建Word文档并下载,无需保存在磁盘中

本文关键字:保存 存在 磁盘 下载 MVC 创建 文档 Word | 更新日期: 2023-09-27 18:14:47

这可能有一个非常简单的答案,但我就是找不到它。

我有一个使用c# MVC 4和Microsoft.Office.Interop.Word 12的项目

在一个动作中,我尝试动态地创建一个Word文件(使用数据库的信息),然后我想下载它。该文件不存在(它是从头创建的),我不想将其保存在磁盘中(它不需要保存,因为它的内容是动态的)。

这是现在的代码:

public ActionResult Generar(Documento documento)
{
    Application word = new Application();
    word.Visible = false;
    object miss = System.Reflection.Missing.Value;
    Document doc = word.Documents.Add(ref miss, ref miss, ref miss, ref miss);
    Paragraph par = doc.Content.Paragraphs.Add(ref miss);
    object style = "Heading 1";
    par.Range.set_Style(ref style);
    par.Range.Text = "This is a dummy test";
    byte[] bytes = null;  // This is the part i need to get the bytes of the doc object
    doc.Close();
    word.Quit();
    return File(bytes, "application/octet-stream", "NewFile.docx");
}

c# MVC 4:创建Word文档并下载,无需保存在磁盘中

使用Robert Harvey推荐的库DocX.dll(谢谢,先生),这将是解决方案:

using Novacode;
using System.Drawing;
.
.
.
public ActionResult Generar(Documento documento)
{
    MemoryStream stream = new MemoryStream();
    DocX doc = DocX.Create(stream);
    Paragraph par = doc.InsertParagraph();
    par.Append("This is a dummy test").Font(new FontFamily("Times New Roman")).FontSize(32).Color(Color.Blue).Bold();
    doc.Save();
    return File(stream.ToArray(), "application/octet-stream", "FileName.docx");
}

我用Microsoft.Office.Interop.Word(这么简单的东西,我很失望)找不到解决方案。

再次感谢Robert,希望这个例子能帮助你解决问题。