带有文件流的 DocX 无法保存



因此,对于一个项目,我正在创建rsamsum 's,我需要将它们保存到docx文件中。它是ASP。对于docx生成,我使用库docx来创建文档。

我可以创建文件,但文件流不添加我放入的内容。

下面是我使用的代码

public ActionResult CVToWord(int id) 
        {
            var CV = CVDAO.CV.Single(cv => cv.id == id);
            var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx";
            System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.OpenOrCreate);
            using (DocX doc = DocX.Create(stream)) 
            {
                Paragraph title = doc.InsertParagraph();
                title.Append(CV.firstname + " " + CV.name);
                doc.Save();
            }
            return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
        }

就像我说的,这创建了文件,但文件没有任何内容。有人知道为什么吗?

public ActionResult CVToWord(int id) 
        {
            var CV = CVDAO.CV.Single(cv => cv.id == id);
            var filename = "CV - " + CV.firstname + " " + CV.name + " - " + CV.creationdate.ToString("dd MM yyyy") + ".docx";
            using (DocX doc = DocX.Create(filename)) 
            {
                Paragraph title = doc.InsertParagraph();
                title.Append(CV.firstname + " " + CV.name);
                doc.Save();
            }
            System.IO.FileStream stream = new System.IO.FileStream(filename, System.IO.FileMode.Open);
            return File(stream, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", filename);
        }
这是

我认为你需要关闭你的FileStream:

stream.Close();

我将为此编写一个自定义ActionResult:

public class CVResult: ActionResult
{
    private readonly CV _cv;
    public CVResult(CV cv)
    {
        _cv = cv;
    }
    public override void ExecuteResult(ControllerContext context)
    {
        var response = context.HttpContext.Response;
        response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        var filename = "CV - " + _cv.firstname + " " + _cv.name + " - " + _cv.creationdate.ToString("dd MM yyyy") + ".docx";
        var cd = new ContentDisposition
        {
            Inline = false,
            FileName = filename
        };
        using (var doc = DocX.Create(response.OutputStream))
        {
            Paragraph title = doc.InsertParagraph();
            title.Append(_cv.firstname + " " + _cv.name);
            doc.Save();
        }
    }
}

,现在您的操作结果不再是乱七八糟的管道代码:

public ActionResult CVToWord(int id) 
{
    var cv = CVDAO.CV.Single(cv => cv.id == id);
    return new CVResult(cv);
}

相关内容

  • 没有找到相关文章

最新更新