mini-software / MiniExcel

Fast, Low-Memory, Easy Excel .NET helper to import/export/template spreadsheet (support Linux, Mac)
https://www.nuget.org/packages/MiniExcel/
Apache License 2.0
2.81k stars 343 forks source link

Hide sheets if Data is empty - using template (SaveAsByTemplateAsync) #656

Open Gilcemir opened 3 months ago

Gilcemir commented 3 months ago

Excel Type

Upload Excel File

Template.xlsx

MiniExcel Version

1.32.1

Description

Please attach your issue file by dragging or droppng, selecting or pasting them.

Hi, Im trying to hide sheets if the data is empty. For example, for the sheet "Mensalidades", if there's nothing to fill the template sheet, I want to hide it.

I did something like this:

        var configuration = new OpenXmlConfiguration()
        {
            IgnoreTemplateParameterMissing = true
        };
        var sheets = HideSheetsIfEmpty(eventData);
        if(sheets.Any())
        {
            configuration.DynamicSheets = sheets;
        }
                await using var memoryStream = new MemoryStream();
        await memoryStream.SaveAsByTemplateAsync(template, value, configuration);
        memoryStream.Seek(0, SeekOrigin.Begin);

        return memoryStream.ToArray();

where:

    private DynamicExcelSheet[] HideSheetsIfEmpty(TransferReportCreatedArgs eventData)
    {
        var sheets = new List<DynamicExcelSheet>();
        if (!eventData.Adjusts.Any())
        {
            sheets.Add(new DynamicExcelSheet(sheetNames["adjust"]) { Name = sheetNames["adjust"], State = SheetState.Hidden });
        }
        if (!eventData.Mensals.Any())
        {
            sheets.Add(new DynamicExcelSheet(sheetNames["mensal"]) { Name = sheetNames["mensal"], State = SheetState.Hidden });
        }
        if (!eventData.Retentions.Any())
        {
            sheets.Add(new DynamicExcelSheet(sheetNames["retention"]) { Name = sheetNames["retention"], State = SheetState.Hidden });
        }
        if (!eventData.OtherProducts.Any())
        {
            sheets.Add(new DynamicExcelSheet(sheetNames["other"]) { Name = sheetNames["other"], State = SheetState.Hidden });
        }
        if (!eventData.Gateways.Any())
        {
            sheets.Add(new DynamicExcelSheet(sheetNames["educbankgateway"]) { Name = sheetNames["educbankgateway"], State = SheetState.Hidden });
        }
        return sheets.ToArray();
    }

Is it possible in any way? Or this configuration is only available for non-template methods?