用openXML下载文件

时间:2017-07-13 13:54:41

标签: c# asp.net file asp.net-web-api openxml

我正在向这个控制器发出请求:

[ResponseType(typeof(Book))]
public async Task<IHttpActionResult> PostBook(Book book)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    string path = "C:\\Users\\af-costa\\Desktop\\TEST.docx";
    var stream = new MemoryStream();

    db.Books.Add(book);
    await db.SaveChangesAsync();

    // New code:
    // Load author name
    db.Entry(book).Reference(x => x.author).Load();

    var dto = new BookDTO()
    {
        Id = book.Id,
        Title = book.Title,
        AuthorName = book.author.name
    };

    Table customTable = createTable(book.author.name, book.Title);
    stream = createDocument(customTable);

    return CreatedAtRoute("DefaultApi", new { id = book.Id }, dto);
}

createDocument检索了一个memoryStream,我基本上需要在openXml的流中下载文件,在这个方法中:

private void createDocument(Table customTable)
{
    var stream = new MemoryStream();
    // Create a Wordprocessing document. 
    using (WordprocessingDocument package = WordprocessingDocument.Create("Test1", WordprocessingDocumentType.Document))
    {
        // Add a new main document part. 
        package.AddMainDocumentPart();

        // Create the Document DOM. 
        package.MainDocumentPart.Document =
          new Document(
            new Body(
              new Paragraph(
                new Run(
                  new Table(customTable)))));

        // Save changes to the main document part. 
        package.MainDocumentPart.Document.Save();
    }
    stream.Seek(0, SeekOrigin.Begin);
}

我不太清楚如何下载该文件,基本上我想用表创建一个文档,并在用户执行请求时下载它 那个接入点。

1 个答案:

答案 0 :(得分:2)

使用您定义的ERROR:

创建word文档
MemoryStream

上一个功能解决了创建Word文件和缓冲数据的需求。现在我们需要获取缓冲的数据并将其作为文本文件发送到客户端。以下代码段显示了如何完成此操作。

private MemoryStream createDocument(Table customTable)
{
    var stream = new MemoryStream();

    // Create a Wordprocessing document. 
    using (WordprocessingDocument package = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document))
    {
        // Add a new main document part. 
        package.AddMainDocumentPart();

        // Create the Document DOM. 
        package.MainDocumentPart.Document =
          new Document(
            new Body(
              new Paragraph(
                new Run(
                  new Table(customTable)))));

        // Save changes to the main document part. 
        package.MainDocumentPart.Document.Save();
    }
    stream.Seek(0, SeekOrigin.Begin);
    return stream;
}

希望这有帮助