问题
Need help bringing my gridview into a excel document. Ive tried several example and can't seem to get it right. Any help would be much appreciated. Here is my gridview code, it is being populated from a SQL database.
<div>
<asp:GridView Align="Center" ID="gvResults" AutoGenerateColumns="false" runat="server" Width="608px"
Style="width: 80%; margin-bottom: 0px" CellPadding="4" ForeColor="#333333" GridLines="None"
OnRowDataBound="gvResults_RowDataBound">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgDataMoreInfo" ImageUrl="T:\Groups\IntResoures\pic\tabpic.jpg" CssClass="img_data_moreinfo" Height="7" Width="7" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Government Name & Address">
<ItemTemplate>
<asp:Label ID="lblGovernmentNameAddress" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="DOB" HeaderText="DOB" />
<asp:TemplateField HeaderText="SSFHS Name & Address">
<ItemTemplate>
<asp:Label ID="lblSSFHSNameAddress" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ssfhsdob" HeaderText="DOB" />
<asp:TemplateField HeaderText="Match Status">
<ItemTemplate>
<asp:RadioButtonList ID="rblMatchStatus" runat="server" RepeatDirection="Vertical"></asp:RadioButtonList>
<asp:Label ID="lblFirst" CssClass="displayNone" runat="server" />
<asp:Label ID="lblSecond" CssClass="displayNone" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" 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>
</div>
My export button and event
<asp:Button ID="btnExportToExcel" OnClick="btnExportToExcel_Click" runat="server" Text="Export to Excel" Width="89px" Font-Size="X-Small" />
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
}
回答1:
Here's a more specific one with respective to your code:
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;
filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
gvResults.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
回答2:
I just did this last week.
Here's the code you'll need to place in your aspx file (you can play with the height and width to your liking):
<asp:Button ID="ButtonA" runat="server" height="20px" OnClick="ButtonA_Click" Text="Export me" Width="200px />
In the Page section at the top of your aspx page insert:
EnableEventValidation="false"
In your cs file place the following below the 'protected void Page_Load...' section:
Protected void ButtonA_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Filename.xls");
Response.ContentType = "application/vnd.xlsx";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Ignore the errors appear and click 'Yes'. The errors appear because the file generated is not pure Excel file type. It produces a file that is essentually text. Save it as a spreadsheet and you'll be good to go.
回答3:
normally while writing to excel as
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
will simply save it as html table to the excel not binary. Check as if you are concern.
there is same problem in my project as well.
then,
- i simply create template of the xcel file empty in my project folder ,
then i write data to it .
string filePath = Server.MapPath("~/ReportFiles/CenterMemberAddressDifferentReport_" + Emp_Session._UserMasterId + ".xls"); System.IO.File.Copy(Server.MapPath("~/Images/ExcelTemplate.xls"), filePath, true); System.Threading.Thread.Sleep(1000); string driver = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + filePath + "';Extended Properties=Excel 8.0;"; System.Data.OleDb.OleDbConnection Con = new System.Data.OleDb.OleDbConnection(driver); System.Data.OleDb.OleDbCommand Com = Con.CreateCommand(); System.Data.OleDb.OleDbDataAdapter reader = new OleDbDataAdapter(); Con.Open(); DataTable dtSheet = Con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); string SQL = ""; foreach (DataRow Row in dt1.Rows) { string values = ""; for (int ik = 0; ik < dt1.Columns.Count; ik++) { if (values != "") values += ","; values += "'" + Row[ik].ToString() + "'"; } SQL = "INSERT INTO [Sheet1$] ([CENTER NAME],[CENTER ADDRESS],[MEMBER ID],[MEMBER NAME],[MEMBER ADDRESS],[MEMBER COUNT]) VALUES(" + values + ")"; Com.CommandText = SQL; Com.ExecuteNonQuery(); } Con.Close(); System.Threading.Thread.Sleep(1000); System.IO.FileStream stream = System.IO.File.OpenRead(filePath); byte[] by = new byte[stream.Length]; stream.Read(by, 0, by.Length); stream.Close(); System.Threading.Thread.Sleep(1000); System.IO.File.Delete(filePath); Response.OutputStream.Write(by, 0, by.Length); Response.End();
basically i was in case of importing the same excel to another datasource and was seccesfull.
Hope it will help you aswell. Plz feedbak are requested. Thank you for the beautifull question.
来源:https://stackoverflow.com/questions/17047296/export-grid-view-to-excel