DataSet/DataGrid导出到excle和csv文件

1.html代码

< HTML >
    
< HEAD >
        
< title > WriteToCVS </ title >
        
< meta  content ="False"  name ="vs_snapToGrid" >
        
< meta  content ="Microsoft Visual Studio .NET 7.1"  name ="GENERATOR" >
        
< meta  content ="C#"  name ="CODE_LANGUAGE" >
        
< meta  content ="JavaScript"  name ="vs_defaultClientScript" >
        
< meta  content ="http://schemas.microsoft.com/intellisense/ie5"  name ="vs_targetSchema" >
    
</ HEAD >
    
< body  MS_POSITIONING ="GridLayout" >
        
< form  id ="Form1"  method ="post"  runat ="server" >
            
< asp:DataGrid  id ="DataGrid1"  style ="Z-INDEX: 101; LEFT: 14px; POSITION: absolute; TOP: 109px"
                runat
="server"  BorderColor ="#CC9966"  BorderStyle ="None"  BorderWidth ="1px"  BackColor ="White"
                CellPadding
="4" >
                
< FooterStyle  ForeColor ="#330099"  BackColor ="#FFFFCC" ></ FooterStyle >
                
< SelectedItemStyle  Font-Bold ="True"  ForeColor ="#663399"  BackColor ="#FFCC66" ></ SelectedItemStyle >
                
< ItemStyle  ForeColor ="#330099"  BackColor ="White" ></ ItemStyle >
                
< HeaderStyle  Font-Bold ="True"  ForeColor ="#FFFFCC"  BackColor ="#990000" ></ HeaderStyle >
                
< PagerStyle  HorizontalAlign ="Center"  ForeColor ="#330099"  BackColor ="#FFFFCC" ></ PagerStyle >
            
</ asp:DataGrid >
            
< asp:Button  id ="Button1"  style ="Z-INDEX: 102; LEFT: 18px; POSITION: absolute; TOP: 11px"  runat ="server"
                Text
="DataSet导出到csv文件"  Width ="148px" ></ asp:Button >
            
< asp:Button  id ="Button2"  style ="Z-INDEX: 103; LEFT: 19px; POSITION: absolute; TOP: 42px"  runat ="server"
                Text
="DataGrid导出到csv文件"  Width ="157px" ></ asp:Button >
            
< asp:Button  id ="Button3"  style ="Z-INDEX: 104; LEFT: 18px; POSITION: absolute; TOP: 73px"  runat ="server"
                Text
="DataGrid导出到Excel"  Width ="149px" ></ asp:Button >
        
</ form >
    
</ body >
</ HTML >

2.cs代码

using  System.IO;
using  System.Data.SqlClient;


public   class  WriteToCVS : System.Web.UI.Page
    
{
        
protected System.Web.UI.WebControls.DataGrid DataGrid1;
        
protected System.Web.UI.WebControls.Button Button2;
        
protected System.Web.UI.WebControls.Button Button3;
        
protected System.Web.UI.WebControls.Button Button1;
    
        
private void Page_Load(object sender, System.EventArgs e)
        
{
            
if(!Page.IsPostBack)
            
{
                
string sql="select * from TestGrid";
                ds
=GetDataSet(sql);
                
this.DataGrid1.DataSource=ds;
                
this.DataGrid1.DataBind();
            }

        }


        
#region WriteDSToCsv 传入dataset生成csv文件
        
public void WriteDSToCsv(DataSet ds)
        
{
            
string strFile="";
            
string path="";            
            DataTable dt
=ds.Tables[0];
            
            
//文件信息设置
            strFile=strFile+"LogBackUp";
            strFile
=strFile+DateTime.Now.ToString("yyyyMMddhhmmss");
            strFile
=strFile+".csv";
            path
=Server.MapPath(strFile);

            
//string[] strHead={"使用者姓名","员工编号","所属分行别","作业时间","使用功能","作业说明"};
            System.IO.FileStream fs=new FileStream(path,System.IO.FileMode.Create,System.IO.FileAccess.Write);
            StreamWriter sw
=new StreamWriter(fs,new System.Text.UnicodeEncoding());
            
//画表头
            for(int i=0;i<dt.Columns.Count;i++)
            
{
                sw.Write(dt.Columns[i].ColumnName);
                sw.Write(
"/t");
            }

            sw.WriteLine(
"");
            
//画表体
            for(int i=0;i<dt.Rows.Count;i++)
            
{
                sw.Write(DelQuota(dt.Rows[i][
"UserID"].ToString()));
                sw.Write(
"/t");
                sw.Write(DelQuota(dt.Rows[i][
"UserName"].ToString()));
                sw.Write(
"/t");                        
                sw.Write(DelQuota(dt.Rows[i][
"provinceID"].ToString()));
                sw.Write(
"/t");
                sw.Write(DelQuota(dt.Rows[i][
"cityID"].ToString()));
                sw.Write(
"/t");
                sw.Write(DelQuota(dt.Rows[i][
"areaID"].ToString()));
                sw.Write(
"/t");
                sw.Write(DelQuota(dt.Rows[i][
"Enabled"].ToString()));                
                sw.WriteLine(
"");
            }

            sw.Flush();
            sw.Close();                
        }


        
#endregion


        
WriteDatagridToCsv 传入datagrid生成csv文件

        
ToExcel

        
#region DelQuota
        
public string DelQuota(string str)//删除特殊字符
        {
            
string result=str;
            
string[] strQuota={"~","!","@","#","$","%","^","&","*","(",")","`",";","'",",",".","/",":","/,","<",">","?"};
            
for(int i=0;i<strQuota.Length;i++)
            
{
                
if(result.IndexOf(strQuota[i])>-1)
                    result
=result.Replace(strQuota[i],"");
            }

            
return result;
        }

        
#endregion


        
#region GetDataSet
        
public static DataSet GetDataSet(string sql)
        
{
            
string ConnectionString=System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"];

            SqlDataAdapter    sda 
=new SqlDataAdapter(sql,ConnectionString);
            DataSet ds
=new DataSet();
            sda.Fill(ds);
            
return ds;
        }

        
#endregion


        
Web Form Designer generated code

        
private void Button1_Click(object sender, System.EventArgs e)
        
{
            WriteDSToCsv(ds);
        }


        
private void Button2_Click(object sender, System.EventArgs e)
        
{
            WriteDatagridToCsv(
this.DataGrid1);        
        }


        
private void Button3_Click(object sender, System.EventArgs e)
        
{
            ToExcel(
this.DataGrid1,"meng");
        }


        
#region property
        
private DataSet ds
        
{
            
get
            
{
                
if(ViewState["ds"]!=null)
                
{
                    
return (DataSet)ViewState["ds"];
                }

                
else
                
{
                    
return null;
                }

            }

            
set
            
{
                ViewState[
"ds"]=value;
            }

        }
        
        
#endregion

    }

3.数据库脚本

if   exists  ( select   *   from  dbo.sysobjects  where  id  =   object_id (N ' [dbo].[TestGrid] ' and   OBJECTPROPERTY (id, N ' IsUserTable ' =   1 )
drop   table   [ dbo ] . [ TestGrid ]
GO

CREATE   TABLE   [ dbo ] . [ TestGrid ]  (
    
[ UserID ]   [ int ]   IDENTITY  ( 1 1 NOT   NULL  ,
    
[ UserName ]   [ nvarchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ provinceID ]   [ nvarchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ cityID ]   [ nvarchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ areaID ]   [ nvarchar ]  ( 50 ) COLLATE Chinese_PRC_CI_AS  NULL  ,
    
[ Enabled ]   [ bit ]   NULL  
ON   [ PRIMARY ]
GO

 wan

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值