#c# #.net-core #syncfusion
#c# #.net-ядро #syncfusion
Вопрос:
Мне нужно сгенерировать документ с несколькими словами и загрузить его на диск, используя цикл foreach. Для документа 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;
}
}
Ответ №1:
На мой взгляд, невозможно отправить несколько «документов» обратно через HTTP.
Вы можете попытаться сохранить файлы в памяти или сохранить их во временной папке, а затем сжать все файлы вместе и вернуть zip-файл пользователю.
Ответ №2:
Для достижения этого требования вы можете добавить документ Word в zip-файл и сохранить документ с несколькими словами в одном zip-файле с помощью Syncfusion.Сжатие. Чтобы удовлетворить ваши требования, мы предлагаем вам использовать приведенный ниже фрагмент кода для загрузки нескольких документов 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.