GridView导出Excel研究

Introduction:

GridView中的数据导出为Excelweb应用中的常见功能。在不同的应用场景下有不同的导出技术。在本文中我将介绍一些导出的技术,希望对您有所帮助

GridView Export the Excel (Basic Code): 

.

首先看一个基础的应用。创建一个表格,见截图


 

然后将数据库中的数据绑定到GridView中的数据,代码如下:

private void BindData()

{

SqlConnection myConnection = new SqlConnection("Server=localhost;Database=School;Trusted_Connection=true");

SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Users", myConnection);

DataSet ds = new DataSet();

ad.Fill(ds);

gvUsers.DataSource = ds;

gvUsers.DataBind();

}

GridViewExportToExcelAllYouNeed2.GIF

现在,GridView中已经绑定了数据,接下来的任务就是导出到Excel。下面是button事件中的代码

Response.ClearContent();

Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

并且还需要override一下VerifyRenderingInServerForm方法(这一点非常重要,否则在点击按钮后会报错,译者注)代码如下:

public override void VerifyRenderingInServerForm(Control control)

{

}

点击导出按钮后会弹出对话框,询问您打开或保存。选择打开文件,导出到Excel的结果如下图:

GridViewExportToExcelAllYouNeed3.GIF

Exporting GridView to Excel With Style:


您是否注意到了以上代码存在一些的问题?是的,ID列开头的0都被截去了。如果你的ID000345,导出后就编程了345。这个问题可以通过把css添加到输出流中来解决。为了使ID列正确显示,您需要将其储存为文本格式。Excel中的文本格式表示为"mso-number-format:"\@"

protected void Btn_ExportClick(object sender, EventArgs e)

{

string style = @"<style> .text { mso-number-format:\@; } </script> ";

Response.ClearContent();

Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);

// Style is added dynamically

Response.Write(style);

Response.Write(sw.ToString());

Response.End();

}

public override void VerifyRenderingInServerForm(Control control)

{

}

 

在上面的代码中,我通过 ”style” 变量来控制 GridView 列的样式。并通过 Respnose.Write 方法将其添加到输出流中。最后把样式添加到 ID 列。这一步需要在 RowDataBound 事件中完成

protected void gvUsers_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.DataRow)

{

e.Row.Cells[1].Attributes.Add("class", "text");

}

}

 

修改的结果如下:

GridViewExportToExcelAllYouNeed4.GIF


Exporting GridView With LinkButtons and Paging: 

如果要导出的GridView中包含LinkButton或者分页(出现分页码时,译者注) 则将出现错误:

GridViewExportToExcelAllYouNeed5.GIF

通过修改页文件可以修正这个问题:EnableEventValidation = "false".

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

看一下导出的文件


GridViewExportToExcelAllYouNeed6.GIF 

在导出的文件中可以看见linkbuttondropdownlist控件,虽然dropdownlist控件显示的数据的确是用户所选的项,但怎么看也不像是一个导出文件(我倒是觉的挺cool的:)译者注),现在应如何移除dropdownlist并显示选择的文字呢?

 


我写了一个 DisableControls 函数,用使循环的方法将 linkbutton dropdownlist 替换成 literal 控件

private void DisableControls(Control gv)

{

LinkButton lb = new LinkButton();

Literal l = new Literal();

string name = String.Empty;

for (int i = 0; i < gv.Controls.Count; i++)

{

if (gv.Controls[i].GetType() == typeof(LinkButton))

{

l.Text = (gv.Controls[i] as LinkButton).Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

else if (gv.Controls[i].GetType() == typeof(DropDownList))

{

l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;

gv.Controls.Remove(gv.Controls[i]);

gv.Controls.AddAt(i, l);

}

 

if (gv.Controls[i].HasControls())

{

DisableControls(gv.Controls[i]);

}

}

}

方法非常简单,只需将linkbutondropdownlist替换成literal控件,并将选择项赋值给literal控件的文本属性。该方法需要在导出前调用

protected void Btn_ExportExcelPaging(object sender, EventArgs e)

{

DisableControls(gvUsers);

Response.ClearContent();

Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();

HtmlTextWriter htw = new HtmlTextWriter(sw);

gvUsers.RenderControl(htw);

Response.Write(sw.ToString());

Response.End();

}

 

现在的Excel中就只剩下选中文本了

GridViewExportToExcelAllYouNeed7.GIF



原文:http://gridviewguy.com/ArticleDetails.aspx?articleID=197

代码下载:GridViewExportToExcelAllYouNeed.zip

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 当使用Java导出Excel文件时,有时会出现文件损坏的问题。这可能是由于文件格式不正确或者文件内容被破坏所致。常见的问题包括Excel打开后是黑底Excel、提示打开是损坏的实际是xlsx,但是后缀显示xls或者实际是xls但是后缀是xlsx等。这些问题一般会出现在使用Office打开Excel时,而使用WPS打开一般不会出现。这是因为WPS兼容了Office的历史版本功能,所以对于任何版本的Excel,WPS都能打开。而Office由于存在Office 2003及以前版本和Office 2007及以后版本的问题,所以会出现以上问题。解决这些问题的方法是确保导出Excel文件的格式正确,并且后缀与实际格式一致。另外,还可以尝试使用WPS来打开导出Excel文件,以确保文件能够正确打开。\[1\] #### 引用[.reference_title] - *1* [java导出excel常见问题(一)--- 导出excel打开异常](https://blog.csdn.net/qq_41154902/article/details/128103022)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [导出GridviewExcel成功但文件已损坏?](https://blog.csdn.net/weixin_34321959/article/details/114842226)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值