惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
DataBreaches.Net
罗磊的独立博客
雷峰网
雷峰网
量子位
V
Visual Studio Blog
Vercel News
Vercel News
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
The Cloudflare Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
宝玉的分享
宝玉的分享
月光博客
月光博客
Martin Fowler
Martin Fowler
aimingoo的专栏
aimingoo的专栏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
腾讯CDC
Engineering at Meta
Engineering at Meta
博客园 - Franky
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
Jina AI
Jina AI
A
About on SuperTechFans

博客园 - 飛雪飄寒

【共享】十步优化SQL Server中的数据访问 【推荐】SQL优化-索引 【推荐】SQL CookBook OLAP函数的使用 通过HttpModule、httpHandlers防止SQL注入式攻击 【分享】Tomcat服务器之安全设置 【分享】.net1.1调用webservice返回二维数组时提示“XML 文档(1, 378)中有错误”的解决方法! .net页面之间传值方式小结 - 飛雪飄寒 - 博客园 在SQLServer中实现ORACLE的Sequence 【共享】将程序制作为服务运行的方法! 【推荐】.NET使用NPOI组件将数据导出Excel 【推荐】Quest.Central.For.Databases——Spotlight的使用 【推荐】[SQL优化工具]Quest.Central.For.Databases——SQL Tuning for SQL Server 【共享】解决“无法显示进程。没有正确安装调试器。请运行安装程序安装或修复调试器。”错误的方法。 【求助】使用SQL语句优化工具遇到的问题 【求助】软考报名即将开始,信息系统项目管理师、系统分析师、系统架构设计师——如何选择? 【探讨】索引视图如何提高性能 .net实现将Excel中的数据导入数据库 【学习】NeatUpload——支持大文件上传的控件
.net导出excel文件操作类续
飛雪飄寒 · 2010-10-29 · via 博客园 - 飛雪飄寒

  在此之前已经写过一篇关于“.net导出wordexcel等文件操作类“的文章详见:http://www.cnblogs.com/dreamof/archive/2008/06/24/1229069.html
  
本文的目的主要是讲讲.net导出excel的技巧及解决以下问题:

  (1)出现导出长串数据(如身份证)EXCEL中后显示为科学计数法的格式,或者报表中显示为001的数据导出到Excel后成了1的格式;

  (2)列宽自适应;

  涉及到的技巧如下:

  (1)       新建一个最原始的DataGrid,对其设置如下:Visible=false,AllowPaging=false;

  (2)       导出数据之前将要导出的数据绑定到DataGrid中;

  (3)       对长数据如身份证、或类似001的数据库进行格式化,转换为文本格式;

  (4)       调用操作类获取DataGrid控件的数据并导出,此时你会发现导出的数据解决了问题(1)并且数据列宽自适应了;

  .net导出excel文件操作类如下:

.net导出excel文件操作类

using System;
using System.Data;
using System.Web;
using System.Text;
using System.IO;namespace GZPI.Service.AgenciesChannel
{
    
/// <summary>
    
/// ExportData 的摘要说明。
    
/// </summary>
    public class ExportData
    {
        
public ExportData()
        {
            
//
            
// TODO: 在此处添加构造函数逻辑
            
//
        }
        
/// <summary>
        
/// 
        
/// </summary>
        
/// <param name="dt"></param>
        
/// <param name="strFileName">含.xls</param>
        public static void ExportDataToExcel(DataTable dt, string FileName)
        {
            
try
            {
                StringWriter sw 
= new StringWriter();
                
string colstr = "";
                
foreach (DataColumn col in dt.Columns)
                {
                    colstr 
+=col.ColumnName + "\t";
                }
                sw.WriteLine(colstr);
foreach (DataRow row in dt.Rows)
                {
                    colstr 
= "";
                    
foreach (DataColumn col in dt.Columns)
                    {
                        colstr 
+=row[col.ColumnName].ToString() + "\t";
                    }
                    sw.WriteLine(colstr);
                }
                sw.Close();
                HttpContext.Current.Response.AppendHeader(
"Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName+ ".xls", System.Text.Encoding.UTF8));
                HttpContext.Current.Response.ContentType 
= "application/ms-excel";    
                System.Web.HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.Default;
                System.Web.HttpContext.Current.Response.Write(sw);
                System.Web.HttpContext.Current.Response.End();
            }
            
catch (Exception ex)
            {
                
throw ex;
            }
        }
public static void ExportDataToExcelByWeb(DataTable dt,System.Web.UI.WebControls.DataGrid DGOutPut,string FileName)
        {
            
try
            {
                DGOutPut.Visible
=true;
                DGOutPut.DataSource
=dt;
                DGOutPut.DataBind();
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.Buffer 
= true;
                System.Web.HttpContext.Current.Response.Charset 
= "GB2312";
                System.Web.HttpContext.Current.Response.AppendHeader(
"Content-Disposition""attachment;filename="+FileName+".xls");
                System.Web.HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
                System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 
                DGOutPut.EnableViewState = false;
                System.Globalization.CultureInfo myCItrad 
= new System.Globalization.CultureInfo("ZH-CN"true);
                System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter(myCItrad);
                System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);
                DGOutPut.RenderControl(oHtmlTextWriter);
                System.Web.HttpContext.Current.Response.Write(oStringWriter.ToString());
                System.Web.HttpContext.Current.Response.End();
                DGOutPut.Visible
=false;
            }
            
catch (Exception ex)
            {
                
throw ex;
            }
        }

    }
}

  实例如下
  1、前台代码:
  <asp:DataGrid id="DGOutPut" runat="server" Visible="False"></asp:DataGrid>
  2、后台代码:  

后台代码

        private void DGOutPut_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                e.Item.Cells[
1].Attributes.Add("style""vnd.ms-excel.numberformat:@");         
            }
        }
private void BtnOutPut_Click(object sender, System.EventArgs e)
        {            
            DataTable dt
=_da.ExecuteDataTable(sql);               
       GZPI.Service.AgenciesChannel.ExportData.ExportDataToExcelByWeb(dt,DGOutPut,
"续办人事代理业务信息");    
        }

  效果图: