随笔 - 31  文章 - 2 评论 - 26 阅读 - 46638
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

在使用ASP.NET做网站时,如果直接在网页上编辑打印数据是很不方便的,因此需要导出Excel供使用者下载编辑。在寻找解决方法时,找了很多资料,经过添加和修改,终于得到令自己满意的代码:
        /*

        
*/

        
private void DataTableExcel(System.Data.DataTable dtData) 
        
{            

            System.Web.UI.WebControls.DataGrid dgExport 
= null
            
// 当前对话 
            System.Web.HttpContext curContext = System.Web.HttpContext.Current; 
            
// IO用于导出并返回excel文件 
            System.IO.StringWriter strWriter = null
            System.Web.UI.HtmlTextWriter htmlWriter 
= null
 
            
if(dtData != null
            
{
                curContext.Response.Clear(); 
                curContext.Response.Buffer
= true
                
// 设置了类型为中文防止乱码的出现
                curContext.Response.Charset="GB2312";    
                System.Globalization.CultureInfo myCItrad 
= new System.Globalization.CultureInfo("ZH-CN",true);
                
// 设置输出流为简体中文
                curContext.Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
                
// 定义输出文件和文件名
                curContext.Response.AppendHeader("Content-Disposition","attachment;filename="+ "QueryResult" +".xls"); 

                
// 设置编码和附件格式 
                curContext.Response.ContentType = "application/vnd.ms-excel"
                
this.EnableViewState = false
      
                
// 导出excel文件
                strWriter = new System.IO.StringWriter(myCItrad); 
                htmlWriter 
= new System.Web.UI.HtmlTextWriter(strWriter); 
 
                
// 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid 
                dgExport = new System.Web.UI.WebControls.DataGrid(); 
                dgExport.DataSource 
= dtData.DefaultView; 
                dgExport.AllowPaging 
= false
                dgExport.DataBind(); 
 
                
// 返回客户端 
                dgExport.RenderControl(htmlWriter);     
                curContext.Response.Write(strWriter.ToString()); 
                curContext.Response.End(); 
            }
 
        }
posted on   烂人  阅读(1626)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示