Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Getting File Wasn't Available On Site . When Iam Generating and Downloading Excel File In Blazor Wasm

$
0
0

I', Using Blazor Wasm 7.0.14 . I Wrote a Code That Will Generate and Download an Excel File From Data In The DataGrid When I Click On a Button .The Problem Is When I Click On The Button Iam Getting "Couldn't Download The File , File Wasn't Available On Site "

**Screen Code **

<style>    .my-header-class .mud-table-cell {        background-color: #92a8d1;        font-size: 1rem;    }</style><MudDataGrid Items="@HorecaInformations" Filterable="true" Virtualize="true" Striped="true" FixedHeader="true" Height="400px"             QuickFilter="@_quickFilter" ColumnResizeMode="ResizeMode.None" Bordered="false" Outlined="true" SortMode="SortMode.Single" FilterMode="DataGridFilterMode.Simple" ><ToolBarContent><MudTextField @bind-Value="_searchString" Placeholder="Search" Adornment="Adornment.Start" Immediate="true"                      AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium" Class="mt-0"></MudTextField><button @onclick="ExportToExcel">            Download</button><a id="exportCsv" class="btn" href="https://localhost:7281/exports/horeca.xlsx" download="horeca.xlsx"           role="button" target="=_top">Export to Excel</a></ToolBarContent><Columns><HierarchyColumn T="GetHorecaInformationsViewModel"  /><PropertyColumn Property="x => x.Id" Title="Id"  Hidden="true"/><PropertyColumn Property="x => x.Name" Title="Name" /><PropertyColumn Property="x => x.Governorate" Title="Governorate" /><PropertyColumn Property="x => x.OwnerName" Title="Owner Name" /><PropertyColumn Property="x => x.OwnerPhone" Title="Owner Phone" /><PropertyColumn Property="x => x.PurcasingManagerName" Title="Purchase Manager Name" /><PropertyColumn Property="x => x.PurchasingManagerPhone" Title="Purchase Manager Phone" /><PropertyColumn Property="x => x.Concept" Title="Concept" /><PropertyColumn Property="x => x.CreatedBy" Title="Created By" /><PropertyColumn Property="x => x.CreatedDate" Title="Created Date" Hideable="true"/><TemplateColumn CellClass="d-flex justify-end" Filterable="false"><CellTemplate><MudStack Row><MudIcon Icon="@Icons.Material.Rounded.RemoveRedEye" Color="Color.Primary" @onclick="() => ShowDetails(context.Item)" /><MudIcon Icon="@Icons.Material.Rounded.Delete" Color="Color.Error" @onclick="() => OnShowButtonClicked(context.Item)" /><a href="@context.Item.Location" target="_blank" class="btn"><MudIcon Icon="@Icons.Material.Rounded.LocationOn" Color="Color.Surface"/></a></MudStack></CellTemplate></TemplateColumn></Columns><ChildRowContent><MudCard><MudCardHeader><CardHeaderContent><MudText Typo="Typo.h6">@context.Item.Name</MudText></CardHeaderContent></MudCardHeader><MudCardContent><MudDataGrid Items="@context.Item.getHorecaStatictsInformationViewModels" Filterable="false" Virtualize="true" Striped="true" Height="300px"><Columns><PropertyColumn Property="x => x.Rating" Title="Rating" /><PropertyColumn Property="x => x.TablesCount" Title="Tables Count" /><PropertyColumn Property="x => x.ChairsCount" Title="Chairs Count" /><PropertyColumn Property="x => x.IsHePasabahceBuyer" Title="Is Pasabahce Buyer" /><PropertyColumn Property="x => x.PasabahcePercentage" Title="Pasabahce Percentage" /><PropertyColumn Property="x => x.IsHeBonnaBuyer" Title="Is Bonna Buyer" /><PropertyColumn Property="x => x.BonnaPercentage" Title="Bonna Percentage" /><PropertyColumn Property="x => x.IsHeNudeBuyer" Title="Is Nude Buyer" /><PropertyColumn Property="x => x.NudePercentage" Title="Nude Percentage" /></Columns></MudDataGrid></MudCardContent></MudCard></ChildRowContent></MudDataGrid><MudMessageBox @ref="mbox" Title="Warning" CancelText="Cancel"><MessageContent>        Deleting can <b>not</b> be undone!</MessageContent><YesButton><MudButton Variant="Variant.Filled" Color="Color.Error" StartIcon="@Icons.Material.Filled.DeleteForever" @onclick="()=>RemoveHoreca()">Delete!</MudButton></YesButton></MudMessageBox>@code {    private Guid selectedItemsId;    private List<GetHorecaInformationsViewModel> HorecaInformations = new List<GetHorecaInformationsViewModel>();    private string _searchString;    MudMessageBox mbox { get; set; }    string state = "Message box hasn't been opened yet";    protected override async Task OnInitializedAsync()    {        HorecaInformations = await httpClient.GetFromJsonAsync<List<GetHorecaInformationsViewModel>>("api/horeca");    }    private Func<GetHorecaInformationsViewModel, bool> _quickFilter => x =>    {        if (string.IsNullOrWhiteSpace(_searchString))            return true;        if (x.Governorate.Contains(_searchString, StringComparison.OrdinalIgnoreCase))            return true;        if (x.Name.Contains(_searchString, StringComparison.OrdinalIgnoreCase))            return true;        if ($"{x.Name} {x.OwnerName} {x.OwnerPhone} {x.PurcasingManagerName} {x.PurchasingManagerPhone} {x.Governorate}".Contains(_searchString))            return true;        return false;    };    private void ShowDetails(GetHorecaInformationsViewModel row)    {        NavigationManager.NavigateTo($"/horeca-details/{row.Id.ToString()}");    }    private async void RemoveHoreca()    {        var result = await httpClient.DeleteAsync($"api/horeca/{selectedItemsId}");        Console.WriteLine(result);    }    private async void OnShowButtonClicked(GetHorecaInformationsViewModel row)    {        selectedItemsId = row.Id;        bool? result = await mbox.Show();    }    private byte[] ProductsToBytes()    {        using var workbook = new XLWorkbook();        var datatable = new DataTable();        datatable.Columns.Add(new DataColumn("Name"));        datatable.Columns.Add(new DataColumn("Governorate"));        datatable.Columns.Add(new DataColumn("OwnerName"));        datatable.Columns.Add(new DataColumn("OwnerPhone"));        datatable.Columns.Add(new DataColumn("PurcasingManagerName"));        datatable.Columns.Add(new DataColumn("PurchasingManagerPhone"));        datatable.Columns.Add(new DataColumn("Concept"));        datatable.Columns.Add(new DataColumn("CreatedBy"));        datatable.Columns.Add(new DataColumn("Rating"));        datatable.Columns.Add(new DataColumn("TablesCount"));        datatable.Columns.Add(new DataColumn("ChairsCount"));        datatable.Columns.Add(new DataColumn("CreatedDate"));        HorecaInformations.ForEach(x =>        {            var newRow = datatable.NewRow();            newRow["Name"] = x.Name;            newRow["Governorate"] = x.Governorate;            newRow["OwnerName"] = x.OwnerName;            newRow["OwnerPhone"] = x.OwnerPhone;            newRow["PurcasingManagerName"] = x.PurcasingManagerName;            newRow["PurchasingManagerPhone"] = x.PurchasingManagerPhone;            newRow["Concept"] = x.Concept;            newRow["CreatedBy"] = x.CreatedBy;            newRow["Rating"] = x.getHorecaStatictsInformationViewModels.FirstOrDefault().Rating;            newRow["TablesCount"] = x.getHorecaStatictsInformationViewModels.FirstOrDefault().TablesCount;            newRow["ChairsCount"] = x.getHorecaStatictsInformationViewModels.FirstOrDefault().ChairsCount;            newRow["CreatedDate"] = x.getHorecaStatictsInformationViewModels.FirstOrDefault().CreatedDate;            datatable.Rows.Add(newRow);        });        var workSheet = workbook.Worksheets.Add(datatable,"HorecaData");        using var memorystream = new MemoryStream();        workbook.SaveAs(memorystream);        return memorystream.ToArray();    }    private void SaveSpreadSheetBytes(byte[] bytes)    {        string rootPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "exports");        Directory.CreateDirectory(rootPath); // Ensure the directory exists        string filePath = Path.Combine(rootPath, "horeca.xlsx");        File.WriteAllBytes(filePath, bytes);    }    public async Task ExportToExcel()     {        var spreadsheetBytes = ProductsToBytes();        SaveSpreadSheetBytes(spreadsheetBytes);        await DownloadFileFromURL();    }    private async Task DownloadFileFromURL()    {        var fileName = "horeca.xlsx";        var fileURL = "https://localhost:7281/exports/horeca.xlsx";        await JS.InvokeVoidAsync("triggerFileDownload", fileName, fileURL);    }}

**Script in index.html File **

<script>        window.triggerFileDownload = (fileName, url) => {            const anchorElement = document.createElement('a');            anchorElement.href = url;            anchorElement.download = fileName ?? '';            anchorElement.click();            anchorElement.remove();        }</script>

Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>