Я использовал один и тот же код в нескольких веб-приложениях для экспорта данных gridview в excel. Обычно работает нормально, но в этом случае, когда я открываю сгенерированный файл excel, заполняется только одна ячейка. Это мой код экспорта:
protected void export_btn_Click(object sender, ImageClickEventArgs e)
{
ExportGridToExcel();
}
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName ="SomeFileName" + DateTime.Now + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType ="application/vnd.ms-excel";
Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);
allDataGridView.GridLines = GridLines.Both;
allDataGridView.HeaderStyle.Font.Bold = true;
allDataGridView.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
Данные в gridview содержат форматирование html, если это имеет значение. Есть много вопросов по экспорту в excel, но для этой конкретной проблемы нет.
EDIT: код Gridview:
<asp:GridView ID="allDataGridView" runat="server" AutoGenerateColumns="False"
CellPadding="4" DataKeyNames="ID" DataSourceID="allDataDataSource"
ForeColor="#333333" Width="795px" Font-Size="X-Small">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="CODE" HeaderText="Code" HtmlEncode="False"
SortExpression="CODE">
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField DataField="DESCRIPTION" HeaderText="Description"
HtmlEncode="False" SortExpression="DESCRIPTION">
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField DataField="TAT" HeaderText="TAT" HtmlEncode="False"
SortExpression="TAT">
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
<asp:BoundField DataField="CONTACT" HeaderText="Contact" HtmlEncode="False"
SortExpression="CONTACT">
<HeaderStyle HorizontalAlign="Left" VerticalAlign="Middle" />
<ItemStyle HorizontalAlign="Left" VerticalAlign="Top" />
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#005293" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
UPDATE: HTML-контент в gridview, похоже, является проблемой. Когда я устанавливаю HTML Encode в False, gridview экспортирует правильно, хотя и с HTML-тегами. Любые идеи о том, как перекодировать его после назначения данных gridview (htmltextwrtter)?
Проблема заключалась в HTML-коде в gridview. Он содержит и теги, после того как они удалены, он экспортирует штраф.
используйте этот код.
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=Demo.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
Label lblheader = new Label();
lblheader.Font.Size = new FontUnit(14, UnitType.Point);
lblheader.Font.Bold = true;
lblheader.Text = "Demo Details";
lblheader.RenderControl(hw);
GrdExcel.Visible = true;
GrdExcel.RenderControl(hw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();
GrdExcel.Visible = false;
Используйте UpdatePanel и триггер.
<Triggers>
<asp:PostBackTrigger ControlID="BtnExcel" />
</Triggers>