Как ни странно, когда я конвертирую поток в массив байтов и обратно в поток, функция работает так, как ожидалось.
Я упускаю здесь что-то фундаментальное?
Это было получено с использованием этого примера MS
Технология:
- Blazor Server .Net 6
- ClosedXML 0.96
async Task ExportToExcel()
{
string fileName = $"DocumentsExport{DateTime.UtcNow.Ticks}.xlsx";
var wb = new ClosedXML.Excel.XLWorkbook();
var ws = wb.AddWorksheet("Documents");
// construct headers
ws.Cell(1, 1).SetValue("Document Name");
ws.Cell(1, 2).SetValue("Description");
ws.Cell(1, 3).SetValue("Sort Order");
ws.Cell(1, 4).SetValue("Category Name");
ws.Cell(1, 5).SetValue("Group Name");
ws.Cell(1, 6).SetValue("Date Modified");
// construct worksheet contents
for (int i = 0; i < documents.Count; i++)
{
var document = documents;
int rowIndex = i + 2;
ws.Cell(rowIndex, 1).SetValue(document.Name);
ws.Cell(rowIndex, 2).SetValue(document.Description);
ws.Cell(rowIndex, 3).SetValue(document.SortOrder);
ws.Cell(rowIndex, 4).SetValue(document.DocumentCategory.Name);
ws.Cell(rowIndex, 5).SetValue(document.DocumentCategory.DocumentGroup.Name);
ws.Cell(rowIndex, 6).SetValue(document.DateModified);
}
// apply formatting and filters
ws.RangeUsed().SetAutoFilter();
ws.Columns().AdjustToContents();
// save file and convert to byte array
// passing this stream to the stream reference causes the file to be downloaded with 0 bytes, thus no content
using MemoryStream ms = new MemoryStream();
wb.SaveAs(ms);
// this line fails
//using var streamRef = new DotNetStreamReference(stream: ms);
// this line works
using var streamRef = new DotNetStreamReference(stream: new MemoryStream(ms.ToArray()));
// execute javaScript to download file
await JS.InvokeVoidAsync("downloadFileFromStream", fileName, streamRef);
}
Код JavaScript:
// script function used to download small files, like excel reports
// https://learn.microsoft.com/en-us/aspne ... etcore-6.0
window.downloadFileFromStream = async (fileName, contentStreamReference) => {
const arrayBuffer = await contentStreamReference.arrayBuffer();
const blob = new Blob([arrayBuffer]);
const url = URL.createObjectURL(blob);
const anchorElement = document.createElement('a');
anchorElement.href = url;
anchorElement.download = fileName ?? '';
anchorElement.click();
anchorElement.remove();
URL.revokeObjectURL(url);
}
Подробнее здесь: https://stackoverflow.com/questions/732 ... rver-fails
Мобильная версия