我花了最近两天试图弄清楚为什么我无法将非常简单的gridview导出到Excel文件或CSV文件中。当我单击导出按钮时,没有任何反应,我没有收到任何错误。起初我尝试了一个导出到excel但没有工作的代码,现在我正在尝试导出到csv文件的代码,它也不起作用。有人可以帮忙吗?谢谢: 这是标记:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="GroupCategory" HeaderText="GroupCategory"
SortExpression="GroupCategory" />
<asp:BoundField DataField="TotalCount" HeaderText="TotalCount"
SortExpression="TotalCount" />
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
这是背后的代码:
public void BindData()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT [GroupCategory], [TotalCount] FROM [Test] ", con);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
// GV_InlineEditing.DataBind();
this.GridView1.DataBind();
}
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
答案 0 :(得分:0)
Public Shared Sub Export(ByVal fileName As String, ByVal gv As GridView, Optional ByVal IncludeFooter As Boolean = True)
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", fileName))
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
HttpContext.Current.Response.Charset = "UTF-8"
Dim sw As StringWriter = New StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
' Create a form to contain the grid
Dim table As Table = New Table
' add the header row to the table
If (Not (gv.HeaderRow) Is Nothing) Then
myGridview.PrepareControlForExport(gv.HeaderRow)
table.Rows.Add(gv.HeaderRow)
End If
' add each of the data rows to the table
For Each row As GridViewRow In gv.Rows
myGridview.PrepareControlForExport(row)
table.Rows.Add(row)
Next
' add the footer row to the table
If IncludeFooter Then
If (Not (gv.FooterRow) Is Nothing) Then
myGridview.PrepareControlForExport(gv.FooterRow)
table.Rows.Add(gv.FooterRow)
End If
End If
' render the table into the htmlwriter
table.RenderControl(htw)
' render the htmlwriter into the response
HttpContext.Current.Response.Write(Replace(sw.ToString, "'", "''"))
HttpContext.Current.Response.End()
End Sub
' Replace any of the contained controls with literals
Private Shared Sub PrepareControlForExport(ByVal control As Control)
Dim i As Integer = 0
Do While (i < control.Controls.Count)
Dim current As Control = control.Controls(i)
If (TypeOf current Is LinkButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, LinkButton).Text))
ElseIf (TypeOf current Is ImageButton) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, ImageButton).AlternateText))
ElseIf (TypeOf current Is HyperLink) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, HyperLink).Text))
ElseIf (TypeOf current Is DropDownList) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, DropDownList).SelectedItem.Text))
ElseIf (TypeOf current Is CheckBox) Then
control.Controls.Remove(current)
control.Controls.AddAt(i, New LiteralControl(CType(current, CheckBox).Checked))
'TODO: Warning!!!, inline IF is not supported ?
End If
If current.HasControls Then
myGridview.PrepareControlForExport(current)
End If
i = (i + 1)
Loop
End Sub
答案 1 :(得分:0)
您可以尝试使用这些命令将DataSet导出到Excel:
public void ConvertDataSetToExcel(DataSet dataSet, string strTempFileName)
{
XmlDocument xmlDataDoc = null;
XslCompiledTransform xslTransform = new XslCompiledTransform();
StreamReader srrReader = null;
XmlTextReader xtrRdr = null;
StringWriter stwWriter = null;
StreamWriter srwWriter = null;
xmlDataDoc = new XmlDocument();
xmlDataDoc.LoadXml(dataSet.GetXml());
srrReader = new StreamReader(path_to_embedded_xsl);
xtrRdr = new XmlTextReader(srrReader);
stwWriter = new StringWriter();
xslTransform.Transform(xmlDataDoc, null, stwWriter);
xslTransform.Transform(xmlDataDoc, null, stwWriter);
srwWriter = new StreamWriter(strTempFileName);
srwWriter.Write(stwWriter.ToString());
srwWriter.Close();
}
请注意,这更多是桌面的实现,因此您必须更改它才能与我们的应用程序一起使用。有关详细信息,请参阅:
http://www.codeproject.com/Articles/9380/Export-a-DataSet-to-Microsoft-Excel-without-the-us http://www.codeproject.com/Articles/11171/DataSet-to-Excel-in-Two-steps-with-Different-Style
答案 2 :(得分:0)
现在一切正常,但是我错了,我甚至忘了添加点击按钮,这就是为什么它没有做任何事情。谢谢所有