iCeSnaker - Program rhapsody

谱写程序的狂想曲

导航

用c#实现将DataGrid中的数据导为microsoft office excel 2003

Posted on 2004-04-22 21:46  iCeSnaker  阅读(4525)  评论(3编辑  收藏  举报

要实现讲datagrid中的数据导为excel,必须引入microsoft的microsoft office webComponent(OWC),从vs.net中引入OWC后,就可以实现将datagrid导为excel.具体的方法如下:
以下是c#代码文件:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace TestExeclFromDataGrid
{
   /// <summary>
   /// WebForm1 的摘要说明。
   /// </summary>
   public class WebForm1 : System.Web.UI.Page
   {
      protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1;
      protected System.Data.SqlClient.SqlCommand sqlSelectCommand1;
      protected System.Data.SqlClient.SqlConnection sqlConnection1;
      protected TestExeclFromDataGrid.dsProdcuts dsProdcuts1;
      protected System.Web.UI.WebControls.Button Button1;
      protected System.Web.UI.WebControls.Label Label1;
      protected System.Web.UI.WebControls.DataGrid DataGrid1;
   
      private void Page_Load(object sender, System.EventArgs e)
      {
         this.sqlDataAdapter1.Fill(this.dsProdcuts1);
         if(!Page.IsPostBack)
         {
            this.DataGrid1.DataBind();
         }// 在此处放置用户代码以初始化页面
      }
      
      public void DataGridToExcel()
      {
         string filesName=this.File1.Value;
         OWC.SpreadsheetClass XlsSheet = new OWC.SpreadsheetClass();//实例化execl中的一张表
         int tempColumn = 0;
         foreach(System.Web.UI.WebControls.DataGridColumn Oitem in this.DataGrid1.Columns)//遍历整个datagrid的每一列,添加表头
         {
XlsSheet.ActiveSheet.Cells[1,tempColumn+1]=Oitem.HeaderText;//添加表头
            tempColumn++;
         }
         for(int i=1;i <= this.DataGrid1.Items.Count;i++)//遍历datagrid中的每一行,
         {
            for(int j=1;j<=this.DataGrid1.Items[i-1].Cells.Count;j++)
            {
               XlsSheet.ActiveSheet.Cells[i+1,j]=this.DataGrid1.Items[i-1].Cells[j-1].Text;//给刚才定义好的excel表没格负值
            }
         }
         XlsSheet.ActiveSheet.Export(filesName,OWC.SheetExportActionEnum.ssExportActionNone);//execl表格的导出
      }

      #region Web Form Designer generated code
      override protected void OnInit(EventArgs e)
      {
         //
         // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
         //
         InitializeComponent();
         base.OnInit(e);
      }
      
      /// <summary>
      /// 设计器支持所需的方法 - 不要使用代码编辑器修改
      /// 此方法的内容。
      /// </summary>
      private void InitializeComponent()
      {
         this.sqlDataAdapter1 = new System.Data.SqlClient.SqlDataAdapter();
         this.sqlSelectCommand1 = new System.Data.SqlClient.SqlCommand();
         this.sqlConnection1 = new System.Data.SqlClient.SqlConnection();
         this.dsProdcuts1 = new TestExeclFromDataGrid.dsProdcuts();
         ((System.ComponentModel.ISupportInitialize)(this.dsProdcuts1)).BeginInit();
         this.Button1.Click += new System.EventHandler(this.Button1_Click);
         //
         // sqlDataAdapter1
         //
         this.sqlDataAdapter1.SelectCommand = this.sqlSelectCommand1;
         this.sqlDataAdapter1.TableMappings.AddRange(new System.Data.Common.DataTableMapping[] {
                                                                            new System.Data.Common.DataTableMapping("Table", "Products", new System.Data.Common.DataColumnMapping[] {
                                                                                                                                                             new System.Data.Common.DataColumnMapping("ProductID", "ProductID"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("ProductName", "ProductName"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("SupplierID", "SupplierID"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("CategoryID", "CategoryID"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("QuantityPerUnit", "QuantityPerUnit"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("UnitPrice", "UnitPrice"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("UnitsInStock", "UnitsInStock"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("UnitsOnOrder", "UnitsOnOrder"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("ReorderLevel", "ReorderLevel"),
                                                                                                                                                             new System.Data.Common.DataColumnMapping("Discontinued", "Discontinued")})});
         //
         // sqlSelectCommand1
         //
         this.sqlSelectCommand1.CommandText = "SELECT ProductID, ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice" +
            ", UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued FROM Products";
         this.sqlSelectCommand1.Connection = this.sqlConnection1;
         //
         // sqlConnection1
         //
         this.sqlConnection1.ConnectionString = "data source=LVYIWEN;initial catalog=Northwind;integrated security=SSPI;persist se" +
            "curity info=False;workstation id=LVYIWEN;packet size=4096";
         //
         // dsProdcuts1
         //
         this.dsProdcuts1.DataSetName = "dsProdcuts";
         this.dsProdcuts1.Locale = new System.Globalization.CultureInfo("zh-CN");
         this.dsProdcuts1.Namespace = "http://www.tempuri.org/dsProdcuts.xsd";
         this.Load += new System.EventHandler(this.Page_Load);
         ((System.ComponentModel.ISupportInitialize)(this.dsProdcuts1)).EndInit();

      }
      #endregion

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


一下是asp.net代码:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="TestExeclFromDataGrid.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
   <HEAD>
      <title>WebForm1</title>
      <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
      <meta name="CODE_LANGUAGE" Content="C#">
      <meta name="vs_defaultClientScript" content="JavaScript">
      <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
   </HEAD>
   <body MS_POSITIONING="GridLayout">
      <form id="Form1" method="post" runat="server">
         <asp:DataGrid id=DataGrid1 style="Z-INDEX: 101; LEFT: 88px; POSITION: absolute; TOP: 88px" runat="server" DataSource="<%# dsProdcuts1 %>" DataKeyField="CategoryID" DataMember="Products" AutoGenerateColumns="False">
            <Columns>
               <asp:BoundColumn DataField="ProductID" SortExpression="ProductID" HeaderText="ProductID"></asp:BoundColumn>
               <asp:BoundColumn DataField="ProductName" SortExpression="ProductName" HeaderText="ProductName"></asp:BoundColumn>
               <asp:BoundColumn DataField="SupplierID" SortExpression="SupplierID" HeaderText="SupplierID"></asp:BoundColumn>
               <asp:BoundColumn DataField="CategoryID" SortExpression="CategoryID" HeaderText="CategoryID"></asp:BoundColumn>
               <asp:BoundColumn DataField="UnitPrice" SortExpression="UnitPrice" HeaderText="UnitPrice"></asp:BoundColumn>
               <asp:BoundColumn DataField="UnitsInStock" SortExpression="UnitsInStock" HeaderText="UnitsInStock"></asp:BoundColumn>
            </Columns>
         </asp:DataGrid>
         <asp:Button id="Button1" style="Z-INDEX: 102; LEFT: 264px; POSITION: absolute; TOP: 280px" runat="server" Text="Button"></asp:Button>
         <asp:Label id="Label1" style="Z-INDEX: 103; LEFT: 200px; POSITION: absolute; TOP: 32px" runat="server" Width="264px">将DataGrid的数据导为excel</asp:Label>
      </form>
   </body>
</HTML>