Blazor 导出到 excel

Adi*_*l15 2 c# excel blazor blazor-server-side

我正在尝试在我的 blazor 服务器端应用程序上添加导出到 excel 按钮。到目前为止,在梳理互联网之后,这就是我所做的。

我的按钮

    <div class="row text-right">
                <div class="col-12 p-3">
                    <button class="btn btn-outline-success" @onclick="@(() =>DownloadExcel(formValues.Region, formValues.startDate, formValues.endDate))">
                        Export to Excel&nbsp;
                        <i class="fa fa-file-excel" aria-hidden="true"></i>
                    </button>
               </div>
            </div>
Run Code Online (Sandbox Code Playgroud)

我的 .razor 页面中的方法

    public FileResult DownloadExcel(string Region, DateTime StartDate, DateTime EndDate)
    {
        FileResult ExcelFile = searchService.ExportToExcel(Region, StartDate, EndDate);
        return ExcelFile;
    }
Run Code Online (Sandbox Code Playgroud)

最后我的服务逻辑

        public FileResult ExportToExcel(string Region, DateTime StartDate, DateTime EndDate)
        {
            var queryable = context.AuditCardPinrecords.Where(s => Region == s.RegionRecordId)
                .Where(s => s.AuditComplete == true)
                .Where(s => s.DateTime >= StartDate && s.DateTime <= EndDate).AsQueryable();

            var stream = new MemoryStream();

            using (var package = new ExcelPackage(stream))
            {
                var workSheet = package.Workbook.Worksheets.Add("Sheet1");
                workSheet.Cells.LoadFromCollection(queryable, true);
                package.Save();
            }


            string excelName = $"AuditPinRecords-{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.xlsx";

            return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName); 

        }
Run Code Online (Sandbox Code Playgroud)

我的预期结果是下载 excel 文件。不幸的是,单击按钮时没有任何反应。任何建议将不胜感激。谢谢!

Bre*_*man 5

我有类似的需求,并且能够通过这个项目的 javascript 拼凑出如何做到这一点:https : //github.com/timplourde/dcidr-blazor

静态实用服务:

public static class ExcelService
{
    public static byte[] GenerateExcelWorkbook()
    {
        var list = new List<UserInfo>()
        {
            new UserInfo { UserName = "catcher", Age = 18 },
            new UserInfo { UserName = "james", Age = 20 },
        };
        var stream = new MemoryStream();

        // ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
        using (var package = new ExcelPackage(stream))
        {
            var workSheet = package.Workbook.Worksheets.Add("Sheet1");

            // simple way
            workSheet.Cells.LoadFromCollection(list, true);

            ////// mutual
            ////workSheet.Row(1).Height = 20;
            ////workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            ////workSheet.Row(1).Style.Font.Bold = true;
            ////workSheet.Cells[1, 1].Value = "No";
            ////workSheet.Cells[1, 2].Value = "Name";
            ////workSheet.Cells[1, 3].Value = "Age";

            ////int recordIndex = 2;
            ////foreach (var item in list)
            ////{
            ////    workSheet.Cells[recordIndex, 1].Value = (recordIndex - 1).ToString();
            ////    workSheet.Cells[recordIndex, 2].Value = item.UserName;
            ////    workSheet.Cells[recordIndex, 3].Value = item.Age;
            ////    recordIndex++;
            ////}

            return package.GetAsByteArray();
        }
    }
}

public class UserInfo
{
    public string UserName { get; set; }
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

js文件夹中的site.js文件创建一个文件wwwroot

function saveAsFile(filename, bytesBase64) {
    var link = document.createElement('a');
    link.download = filename;
    link.href = "data:application/octet-stream;base64," + bytesBase64;
    document.body.appendChild(link); // Needed for Firefox
    link.click();
    document.body.removeChild(link);
}
Run Code Online (Sandbox Code Playgroud)

在您的 _Host.cshtml 文件的正文部分中添加以下脚本

<script src="~/js/site.js"></script>
Run Code Online (Sandbox Code Playgroud)

在您要从中导出为 excel 的 .razor 页面中

@using YOUR_APP_NAME.Services

@inject IJSRuntime js

<Row Class="d-flex px-0 mx-0 mb-1">
    <Button Clicked="@DownloadExcelFile" class="p-0 ml-auto mr-2" style="background-color: transparent" title="Download">
        <span class="fa fa-file-excel fa-lg m-0" style="color: #008000; background-color: white;" aria-hidden="true"></span>
    </Button>
</Row>

@code {
    private void DownloadExcelFile()
    {
        var excelBytes = ExcelService.GenerateExcelWorkbook();
        js.InvokeVoidAsync("saveAsFile", $"test_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.xlsx", Convert.ToBase64String(excelBytes));
    }
}
Run Code Online (Sandbox Code Playgroud)


Ed *_*eau 1

.razor 组件不像 MVC 视图那样是 HTTP 端点。您返回的 FileResult 不会触发浏览器下载。

您将需要创建一个 MVC 控制器操作并将用户重定向到那里,或者使用 JavaScript 调用文件保存操作。然后,您需要使用 JavaScript Interop 来调用 JS 函数。

window.msSaveBlob = function (payload, filename) {

    const createBlob = data => new Blob([data], { type: "text/csv;charset=utf-8;" });

    const buildDownloadLink = (blob, fileName) => {
        let link = document.createElement("a");
        link.setAttribute("href", URL.createObjectURL(blob));
        link.setAttribute("download", fileName);
        link.style = "visibility:hidden";
        return link;
    };
    const invokeDownload = link => {
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };
    const isHtmlDownloadAllowed = document.createElement("a").download !== undefined;
    const isSaveBlobAllowed = navigator.msSaveBlob;

    isSaveBlobAllowed ? navigator.msSaveBlob(createBlob(payload), filename) :
        isHtmlDownloadAllowed ? invokeDownload(buildDownloadLink(createBlob(payload), filename)) :
            console.log("Feature unsupported");

};
Run Code Online (Sandbox Code Playgroud)

当然,也有商业图书馆可以帮助处理这些类型的事情。用于 Blazor 文档处理的 Telerik UI