We would like to set the width of columns in xlsx export from a RadGrid. I do this by using e.ExportStructure.Tables[0].Columns in the InfrastructureExporting event handler. If columns are declaratively set in the aspx file when this works fine.
If, however, the columns of the RadGrid are added by setting AutoGenerateColumns="true" or manually in Page_Load, then the Columns collection is empty. Why is this, and are there some other way to set the width of the columns in the xlsx file?
ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="true" OnNeedDataSource="RadGrid1_NeedDataSource" OnInfrastructureExporting="RadGrid1_InfrastructureExporting">
<ExportSettings Excel-Format="Xlsx" />
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" />
.cs:
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
}
protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = new List<Person> {
new Person { ID = "1", Name = "Adam", Date = new DateTime(1973, 4, 12) },
new Person { ID = "2", Name = "Bertil", Date = null },
new Person { ID = "3", Name = "Ceasar", Date = new DateTime(1973, 10, 27) },
};
}
protected void Button1_Click(object sender, EventArgs e)
{
RadGrid1.MasterTableView.ExportToExcel();
}
protected void RadGrid1_InfrastructureExporting(object sender, Telerik.Web.UI.GridInfrastructureExportingEventArgs e)
{
e.ExportStructure.ColumnWidthUnit = Telerik.Web.UI.ExportInfrastructure.ExportUnitType.FormatDefault;
// ERROR: The Columns collection is empty if the columns of radgrid are auto-generated or dynamically added in code behind
foreach (var col in e.ExportStructure.Tables[0].Columns)
{
col.Width = 20;
}
}
/Patrik