带有文件流的DocX无法保存

时间:2011-10-03 11:10:06

标签: c# asp.net-mvc asp.net-mvc-3 filestream docx

因此,对于我正在创建简历的项目,我需要将它们保存到docx文件中。 它是一个ASP.NET MVC应用程序,对于docx生成我正在使用libray 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);
        }

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

3 个答案:

答案 0 :(得分:1)

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);
        }

这有效

答案 1 :(得分:0)

我认为您需要关闭FileStream:

stream.Close();

答案 2 :(得分:0)

我会为此编写一个自定义的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);
}