DataGrid导出Excel(c#)

来源:互联网 发布:php 数组合并 覆盖 编辑:程序博客网 时间:2024/04/24 11:25

 WebForm1.aspx

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="baolong.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
 <HEAD>
  <title>WebForm1</title>
  <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 style="FONT-SIZE: 9pt" MS_POSITIONING="GridLayout">
  <form id="Form1" method="post" runat="server">
   <asp:label id="Label1" runat="server"></asp:label><asp:textbox id="xlfile" Runat="server"></asp:textbox><br>
   <br>
   <asp:button id="ExportDataBase2Excel" Runat="server"></asp:button><asp:button id="ExportDataGrid2Excel" Runat="server"></asp:button><br>
   <asp:datagrid id="DataGrid1" runat="server" CellPadding="4" BackColor="White" BorderWidth="1px"
    BorderStyle="None" BorderColor="#CC9966" AutoGenerateColumns="False">
    <ItemStyle ForeColor="#330099" BackColor="White"></ItemStyle>
    <HeaderStyle Font-Bold="True" ForeColor="#FFFFCC" BackColor="#990000"></HeaderStyle>
    <Columns>
     <asp:BoundColumn DataField="Title"></asp:BoundColumn>
     <asp:BoundColumn DataField="Author"></asp:BoundColumn>
    </Columns>
   </asp:datagrid></form>
 </body>
</HTML>

 WebForm1.aspx.cs

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using OWC;
using System.Data.SqlClient;

namespace baolong
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.TextBox xlfile;
  protected System.Web.UI.WebControls.Button ExportDataBase2Excel;
  protected System.Web.UI.WebControls.Button ExportDataGrid2Excel;
    
  
        public static  SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DBString"].ToString());
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  private SqlCommand comm=new SqlCommand("SELECT TOP 50 Title,Author FROM Document",conn);
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!Page.IsPostBack)
   {
    BindDataGrid();
    Label1.Text = "请输入要保存得文件名字:";
    ExportDataGrid2Excel.Text = "由DataGrid生成Excel文件";
                ExportDataBase2Excel.Text = "数据库直接生成Excel文件";
    DataGrid1.Columns[0].HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                DataGrid1.Columns[0].HeaderText = "文章名称";
                DataGrid1.Columns[1].HeaderText = "作者";
                DataGrid1.Columns[0].HeaderStyle.Font.Bold = true;
                DataGrid1.Style.Add("font-size", "9pt");


   }
  }
  private void BindDataGrid()
  {
      conn.Open();
   SqlDataReader dr=comm.ExecuteReader();
   DataGrid1.DataSource = dr;
             DataGrid1.DataBind();
   dr.Close();
   conn.Close();
          
  }
  private void WriteDataBase2Excel()
  {
  SpreadsheetClass xlsheet=new SpreadsheetClass();
   conn.Open();
   SqlDataReader dr=comm.ExecuteReader();
   int numbercols=dr.FieldCount;
   int row=2;
   int i;
   for(i=0;i<numbercols;i++)
   {
    xlsheet.ActiveSheet.Cells[1,i+1]=dr.GetName(i).ToString();
   }
   while(dr.Read())
   {
    for(i=0;i<numbercols;i++)
    {
    xlsheet.ActiveSheet.Cells[row,i+1]=dr.GetValue(i).ToString();
     
    }
    row=row+1;
   }
          dr.Close();
         conn.Close();
   try
   {
    xlsheet.ActiveSheet.Export(Server.MapPath(".")+"/Files/"+xlfile.Text.Trim()+".xls",OWC.SheetExportActionEnum.ssExportActionNone);

   }
   catch(System.Runtime.InteropServices.COMException ex)
   {
   Response.Write("错误:" + ex.Message);

   }
  }
  private void WriteDataGrid2Excel()
  {
  SpreadsheetClass xlsheet=new SpreadsheetClass();
   int i=0;
   int j=0;
   //Response.End();
            //输出标题;
   foreach(DataGridColumn oItem in DataGrid1.Columns)
   {
   xlsheet.ActiveSheet.Cells[1,i + 1] = oItem.HeaderText;
   //xlsheet.ActiveSheet.Range(xlsheet.ActiveSheet.Cells(1, 1),xlsheet.ActiveSheet.Cells(1, i + 1)).Font.Bold = True;
      //xlsheet.get_Range(xlsheet.Cells[1, i], xlsheet.Cells[1, i + 1]);
            //xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[1, i + 1]);
   i=i+1;
   }
   int numbercols=DataGrid1.Items[0].Cells.Count;
   for(j=0;j<DataGrid1.Items.Count;j++)
   {
    for(i=0;i<numbercols;i++)
    {
       // xlsheet.get_Range(xlsheet.Cells[2, 2], xlsheet.Cells[j + 2, i + 1]).Font.Color = "blue";
        //xlsheet.Range("A2:B14").WrapText = True;
     xlsheet.get_Range(xlsheet.Cells[2, 1], xlsheet.Cells[j + 2, i + 1]).AutoFitColumns();
     xlsheet.ActiveSheet.Cells[j + 2, i + 1] = DataGrid1.Items[j].Cells[i].Text.Replace("&nbsp;", " ");
    }
   }
   try
   {
    xlsheet.ActiveSheet.Export(Server.MapPath(".")+"/Files/"+xlfile.Text+".xls",OWC.SheetExportActionEnum.ssExportActionNone);------注意Files的权限为完全控制

   }
   catch(System.Runtime.InteropServices.COMException ex)
   {
    Response.Write("错误:" + ex.Message);

   }
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.ExportDataBase2Excel.Click += new System.EventHandler(this.ExportDataBase2Excel_Click);
   this.ExportDataGrid2Excel.Click += new System.EventHandler(this.ExportDataGrid2Excel_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void ExportDataBase2Excel_Click(object sender, System.EventArgs e)
  {
   if(xlfile.Text.Trim()!="")
   {
   WriteDataBase2Excel();
   }        
  }

  private void ExportDataGrid2Excel_Click(object sender, System.EventArgs e)
  {
   if(xlfile.Text.Trim()!="")
   {
    WriteDataGrid2Excel();
   } 
  }
 }
}
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using OWC;
using System.Data.SqlClient;

namespace baolong
{
 /// <summary>
 /// WebForm1 的摘要说明。
 /// </summary>
 public class WebForm1 : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Label Label1;
  protected System.Web.UI.WebControls.TextBox xlfile;
  protected System.Web.UI.WebControls.Button ExportDataBase2Excel;
  protected System.Web.UI.WebControls.Button ExportDataGrid2Excel;
    
  
        public static  SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["DBString"].ToString());
  protected System.Web.UI.WebControls.DataGrid DataGrid1;
  private SqlCommand comm=new SqlCommand("SELECT TOP 50 Title,Author FROM Document",conn);
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!Page.IsPostBack)
   {
    BindDataGrid();
    Label1.Text = "请输入要保存得文件名字:";
    ExportDataGrid2Excel.Text = "由DataGrid生成Excel文件";
                ExportDataBase2Excel.Text = "数据库直接生成Excel文件";
    DataGrid1.Columns[0].HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                DataGrid1.Columns[0].HeaderText = "文章名称";
                DataGrid1.Columns[1].HeaderText = "作者";
                DataGrid1.Columns[0].HeaderStyle.Font.Bold = true;
                DataGrid1.Style.Add("font-size", "9pt");


   }
  }
  private void BindDataGrid()
  {
      conn.Open();
   SqlDataReader dr=comm.ExecuteReader();
   DataGrid1.DataSource = dr;
             DataGrid1.DataBind();
   dr.Close();
   conn.Close();
          
  }
  private void WriteDataBase2Excel()
  {
  SpreadsheetClass xlsheet=new SpreadsheetClass();
   conn.Open();
   SqlDataReader dr=comm.ExecuteReader();
   int numbercols=dr.FieldCount;
   int row=2;
   int i;
   for(i=0;i<numbercols;i++)
   {
    xlsheet.ActiveSheet.Cells[1,i+1]=dr.GetName(i).ToString();
   }
   while(dr.Read())
   {
    for(i=0;i<numbercols;i++)
    {
    xlsheet.ActiveSheet.Cells[row,i+1]=dr.GetValue(i).ToString();
     
    }
    row=row+1;
   }
          dr.Close();
         conn.Close();
   try
   {
    xlsheet.ActiveSheet.Export(Server.MapPath(".")+"/Files/"+xlfile.Text.Trim()+".xls",OWC.SheetExportActionEnum.ssExportActionNone);

   }
   catch(System.Runtime.InteropServices.COMException ex)
   {
   Response.Write("错误:" + ex.Message);

   }
  }
  private void WriteDataGrid2Excel()
  {
  SpreadsheetClass xlsheet=new SpreadsheetClass();
   int i=0;
   int j=0;
   //Response.End();
            //输出标题;
   foreach(DataGridColumn oItem in DataGrid1.Columns)
   {
   xlsheet.ActiveSheet.Cells[1,i + 1] = oItem.HeaderText;
   //xlsheet.ActiveSheet.Range(xlsheet.ActiveSheet.Cells(1, 1),xlsheet.ActiveSheet.Cells(1, i + 1)).Font.Bold = True;
      //xlsheet.get_Range(xlsheet.Cells[1, i], xlsheet.Cells[1, i + 1]);
            //xlsheet.get_Range(xlsheet.Cells[1, 1], xlsheet.Cells[1, i + 1]);
   i=i+1;
   }
   int numbercols=DataGrid1.Items[0].Cells.Count;
   for(j=0;j<DataGrid1.Items.Count;j++)
   {
    for(i=0;i<numbercols;i++)
    {
       // xlsheet.get_Range(xlsheet.Cells[2, 2], xlsheet.Cells[j + 2, i + 1]).Font.Color = "blue";
        //xlsheet.Range("A2:B14").WrapText = True;
     xlsheet.get_Range(xlsheet.Cells[2, 1], xlsheet.Cells[j + 2, i + 1]).AutoFitColumns();
     xlsheet.ActiveSheet.Cells[j + 2, i + 1] = DataGrid1.Items[j].Cells[i].Text.Replace("&nbsp;", " ");
    }
   }
   try
   {
    xlsheet.ActiveSheet.Export(Server.MapPath(".")+"/Files/"+xlfile.Text+".xls",OWC.SheetExportActionEnum.ssExportActionNone););------注意Files的权限为完全控制

   }
   catch(System.Runtime.InteropServices.COMException ex)
   {
    Response.Write("错误:" + ex.Message);

   }
  }
  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {   
   this.ExportDataBase2Excel.Click += new System.EventHandler(this.ExportDataBase2Excel_Click);
   this.ExportDataGrid2Excel.Click += new System.EventHandler(this.ExportDataGrid2Excel_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void ExportDataBase2Excel_Click(object sender, System.EventArgs e)
  {
   if(xlfile.Text.Trim()!="")
   {
   WriteDataBase2Excel();
   }        
  }

  private void ExportDataGrid2Excel_Click(object sender, System.EventArgs e)
  {
   if(xlfile.Text.Trim()!="")
   {
    WriteDataGrid2Excel();
   } 
  }
 }
}

原创粉丝点击