Skip to content

Conversation

@Discolai
Copy link
Contributor

@Discolai Discolai commented Nov 15, 2024

Closes #682
Closes #379

This PR implements writing excel documents with auto column width. The required width is an estimate based on the string length and an average factor based on the Calibri font with size 11pt.

@shps951023 shps951023 merged commit 0b15822 into mini-software:master Nov 22, 2024
3 checks passed
@shps951023
Copy link
Member

❤ Reviewed & Merged, please feel free to feedback

@stian-bay
Copy link

Could this also check the header column width? The header can be longer than the data. Im setting the header name in the data model like this [ExcelColumn(Name = "My longer column header", Index = 0)]

@Narendin
Copy link

@stian-bay try this

List<Dictionary<string, object>> data; // data to export

var headers = data.SelectMany(x => x.Keys).Distinct().Select(x => new DynamicExcelColumn(x)
{
    Width = ExcelWidthCollection.GetApproximateRequiredCalibriWidth(x.Length)
}).ToArray();

var config = new OpenXmlConfiguration
{
    EnableAutoWidth = true,
    FastMode = true,
    DynamicColumns = headers
};

MiniExcel.SaveAs(path, data, configuration: config);

@stian-bay
Copy link

@stian-bay try this


List<Dictionary<string, object>> data; // data to export



var headers = data.SelectMany(x => x.Keys).Distinct().Select(x => new DynamicExcelColumn(x)

{

    Width = ExcelWidthCollection.GetApproximateRequiredCalibriWidth(x.Length)

}).ToArray();



var config = new OpenXmlConfiguration

{

    EnableAutoWidth = true,

    FastMode = true,

    DynamicColumns = headers

};



MiniExcel.SaveAs(path, data, configuration: config);

Ah cool, I will try this. Thanks

@stian-bay
Copy link

Got it working in my dynamic method like this. Maybe a little more complex, but this seems to be working great 🎉

public static MemoryStream Export<T>(IEnumerable<T> data)
{
    var columns = typeof(T)
        .GetProperties()
        .Select(p => new { Property = p, Attribute = p.GetCustomAttribute<ExcelColumnAttribute>() })
        .Select(x => new DynamicExcelColumn(x.Property.Name)
        {
            Name = x.Attribute?.Name,
            Width = ExcelWidthCollection.GetApproximateTextWidth(x.Attribute?.Name?.Length ?? x.Property.Name.Length) + 1
        })
        .ToArray();

    var config = ExportSettings.DefaultConfiguration;

    config.DynamicColumns = columns;

    var memoryStream = new MemoryStream();
    memoryStream.SaveAs(data, configuration: config);
    memoryStream.Seek(0, SeekOrigin.Begin);

    return memoryStream;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto adjust column width for excel writing AutoFit for Column Width

4 participants