将GridView内数据导入到Excel

来源:互联网 发布:一键搬家软件 编辑:程序博客网 时间:2024/04/19 12:52

以下是导出数据的后台类:

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

namespace WebUtility
{
    
/// <summary>
    
/// 将Table的数据导出Excel;
    
/// 标题为Table的标题;
    
/// 使用文件操作来完成此功能:
    
/// 缺点:不能操作Excel;标题可能是英文,没有边框,没有格式;
    
/// </summary>

    public class OutExcel:DBUtility.DBHelper
    
{
        
/// <summary>
        
/// 导出EXCEL
        
/// </summary>
        
/// <param name="dt"></param>
        
/// <param name="FileName"></param>
        
/// <returns></returns>

        public int Export(DataTable dt,string FileName)
        
{
            
try
            
{
                
//文件名;创建;可写
                FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write); 
                StreamWriter sw
=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
                
//标题
                string Title = "";
                
//内容
                string Line = "";
                
for (int i=0;i<dt.Columns.Count;i++)
                
{
                    Title 
= Title + dt.Columns[i].ToString() + " ";
                }

                
//去掉最后的回车符
                Title = Title.Substring(0,Title.Length -1);
                
//将标题写入流
                sw.WriteLine(Title); 
                
foreach(DataRow dr in dt.Rows) 
                

                    
for (int i=0;i<dt.Columns.Count;i++)
                    
{
                        Line 
= Line+dr[i] + " ";
                    }

                    Line 
= Line.Substring(0,Line.Length -1);
                    
//将数据写入文件流
                    sw.WriteLine(Line); 
                    Line 
= "";
                }
 
                sw.Close();
                
return 0;
            }

            
catch
            
{
                
return 1;
            }

        }

        
//===============================================================================================
    }

}

 在页面上进行调用:
protected void btnOut_Click(object sender, EventArgs e)
    
{
        
public WebUtility.OutExcel myOut = new WebUtility.OutExcel();
        
//导出日志到Excel
        System.Data.DataTable dt = user.DataSetLoginLog(WebUtility.SysUser.LoginLogType.all).Tables[0];
        
string DownloadPath = Server.MapPath("."+ "//" + string.Format("登录日志备份{0}.XLS",System.DateTime.Now.ToShortDateString());
        
//导出
        this.myOut.Export(dt, DownloadPath);
        
//以下代码将 pdf 文件写入客户端浏览器。
        Response.ClearContent();
        Response.ClearHeaders();
        
//作为附件下载
        Response.AddHeader("Content-Disposition""attachment; filename=" + Server.UrlEncode(DownloadPath));
        Response.ContentType 
= "application/ms-excel";
        Response.WriteFile(DownloadPath);
        Response.Flush();
        Response.Close();
        
//从磁盘删除导出的文件
        System.IO.File.Delete(DownloadPath);
    }