簡體   English   中英

從foreach循環生成多個word文檔

[英]Generate multiple word document from foreach loop

我需要使用 foreach 循環生成多個 word 文檔並下載到磁盤。 對於 Word 文檔,我使用的是 Syncfusion。 我只能從我的程序中下載一個文檔。 那是因為我在循環中使用了 return 語句。 返回后如何繼續循環,或者有任何方法可以在循環內不返回的情況下執行此操作? 這是我的代碼

public async Task<IActionResult> CreateDocument(int? id)
    {
        string text = "some text"
        List<OrderUser> teamList = await _context.OrderUser.Where(o => o.OrderId == id).Include(o => o.Order).Include(o => o.ApplicationUser).ToListAsync();
        using (WordDocument document = new WordDocument())
        {
            IWSection section = document.AddSection();
            IWParagraph paragraph = section.AddParagraph();

            paragraph.AppendText(text);

            foreach (var item in teamList)
            {
                paragraph.AppendText("Mr " + item.ApplicationUser.DisplayName);
                MemoryStream stream = new MemoryStream();

                document.Save(stream, FormatType.Docx);

                stream.Position = 0;

                return File(stream, "application/msword", "Result.docx");
            }

            return null;
        }
    }

在我看來,不可能通過 HTTP 發回多個“文檔”。

您可以嘗試將文件保存在內存中或將它們存儲在一個臨時文件夾中,然后將所有文件壓縮在一起並將 zip 文件返回給用戶。

要實現此要求,您可以將 Word 文檔添加到 zip 文件中,並使用 Syncfusion.Compression 將多個 Word 文檔保存在單個 zip 文件中。 為了滿足您的要求,我們建議您使用以下代碼片段一次性下載多個 Word 文檔。

public IActionResult Index(string button)
{
if (button == null)
return View();

string text = "some text";
List<string> items = new List<string>(){ "First","Second","Third","Fourth"};
//Initializes new instance of ZipAchive
ZipArchive zipArchive = new Syncfusion.Compression.Zip.ZipArchive();
//Sets compression level for new items
zipArchive.DefaultCompressionLevel = Syncfusion.Compression.CompressionLevel.Best;
for(int i=0;i<items.Count;i++)
{
using (WordDocument document = new WordDocument())
{
//Adds new section to the document
IWSection section = document.AddSection();
//Add new paragraph to the section
IWParagraph paragraph = section.AddParagraph();
//Appends the specified text to the paragraph
paragraph.AppendText(text);
paragraph.AppendText(items[i]);
MemoryStream stream = new MemoryStream();
//Save the document
document.Save(stream, FormatType.Docx);
stream.Position = 0;
//Adds new item to the archive
zipArchive.AddItem("Sample"+i.ToString()+ ".docx", stream, false, (Syncfusion.Compression.FileAttributes)FileAttributes.Normal);
}
}
//Zips the filename
MemoryStream memoryStream = new MemoryStream();
//Saves the zip file
zipArchive.Save(memoryStream, false);
return File(memoryStream.ToArray(), "application/zip", "Attachments.zip");
} 

更多信息請參考: https : //www.syncfusion.com/kb/1922/is-it-possible-to-create-the-zip-files-using-syncfusion-compression-zip

注意:適用於 Syncfusion。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM