1.datagrid导出到excel,用如下代码
public void ExportToExcel(System.Web.UI.Control ctl) 
        { 
            bool CurrCtlVisible=ctl.Visible;
            ctl.Visible=true;        Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");  
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Response.ContentType = "application/ms-excel"; 
            ctl.Page.EnableViewState = false; 
            System.IO.StringWriter tw = new System.IO.StringWriter(); 
            System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw); 
            ctl.RenderControl(hw); 
            Response.Write(tw.ToString()); 
            Response.End(); 
            
            ctl.Page.EnableViewState = true; 
            ctl.Visible=CurrCtlVisible;
        }该如何调用它?是否用一个asp:button将onclick事件写成ExportToExcel就行了,那它怎么判断我要导出哪一个datagrid,如果我的页面有2个datagrid它会导出哪个?2.datagrid中我使用了<div>自动显示scroll,但当向下滚动时,表头也跟着滚动不见了,请问如何在我向下滚动时表头可以固定,不会向下滚动。3.能否实现datagrid表脚的查询和表体的查询不同,举个例子:表体显示记录,表脚显示合计,能否分别绑定不同的sql语句?如果不行,我写个存储过程来实现它,那么当datagrid有多页时,如何让表脚出现在每一页中且都不会改变?4.如何实现双击datagrid中某一行将该行的数据传送到另外一个页面中去编辑,类似于查询单据页面,双击某张单据,可以跳到一个页面中对它进行编辑的操作

解决方案 »

  1.   

    1.datagrid中我使用了<div>自动显示scroll,但当向下滚动时,表头也跟着滚动不见了,请问如何在我向下滚动时表头可以固定,不会向下滚动。2.能否实现datagrid表脚的查询和表体的查询不同,举个例子:表体显示记录,表脚显示合计,能否分别绑定不同的sql语句?如果不行,我写个存储过程来实现它,那么当datagrid有多页时,如何让表脚出现在每一页中且都不会改变?3.如何实现双击datagrid中某一行将该行的数据传送到另外一个页面中去编辑,类似于查询单据页面,双击某张单据,可以跳到一个页面中对它进行编辑的操作
      

  2.   

    3。用以下方法绑定数据
    ICollection CreateDataSource() 
    {
        DataTable dt = new DataTable();
        DataRow dr;
        dt.Columns.Add(new DataColumn("身份证号码", typeof(string)));
        dt.Columns.Add(new DataColumn("图书单价",typeof(decimal)));
        dt.Columns.Add(new DataColumn("购买数量",typeof(Int32)));
        dt.Columns.Add(new DataColumn("总价格",typeof(decimal)));    for (int i = 0; i < 30; i++) 
        {
            dr = dt.NewRow();
            dr[0] = "123456789123456789";
            dr[1] = 100 * i /3.0;
            dr[2] = i + 5;
            dr[3] = (decimal)dr[1] * (Int32)dr[2];
            dt.Rows.Add(dr);
        }
        DataView dv = new DataView(dt);
        return dv;
    }DataGrid1.DataSource=CreateDataSource();
    DataGrid1.DataBind();
      

  3.   

    if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
    {
                 e.Item.Cells[3].Attributes.Add("onclick","window.open('clinic.aspx');");
              }
      

  4.   

    在Web From上输出数据到Excel有两种方法,一个是有数据库直接导出;另外一个方法是由DataGrid直接输出到Excel文件。下面得代码实现了这两个功能。注意:在使用时要引用Microsoft Office Web Components 9.0 COM组件,另外注意设置要保存文件得目录具有匿名可修改的权限。DataGridToExcel.aspx<%@ Page Language="vb" EnableViewState="False" AutoEventWireup="false" Codebehind="DataGridToExcel.aspx.vb"
     Inherits="aspxWeb.mengxianhui.com.DataGridToExcel"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
      <HEAD>
        <title id="mengxianhui" runat="server"></title>
        <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0">
        <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
      </HEAD>
      <body MS_POSITIONING="GridLayout" style="FONT-SIZE:9pt">
        <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 ID="ExportDataGrid2Excel" Runat="server" />
          <br>
          <asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" BorderColor="#CC9966"
           BorderStyle="None" BorderWidth="1px" BackColor="White" CellPadding="4">
            <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>DataGridToExcel.aspx.vbImports System
    Imports System.Data
    Imports System.Data.OleDb
    Imports OWCPublic Class DataGridToExcel
      Inherits System.Web.UI.Page
      Protected WithEvents xlfile As System.Web.UI.WebControls.TextBox
      Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid
      Protected WithEvents ExportDataGrid2Excel As System.Web.UI.WebControls.Button
      Protected WithEvents ExportDataBase2Excel As System.Web.UI.WebControls.Button
      Protected WithEvents Label1 As System.Web.UI.WebControls.Label
      Protected mengxianhui As New HtmlGenericControl()  Private cnn As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="_
       + Server.MapPath("Test.mdb"))
      Private sql As OleDbCommand = New OleDbCommand("SELECT TOP 50 Title,Author FROM Document", cnn)#Region " Web Form Designer Generated Code "  'This call is required by the Web Form Designer.
      <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()  End Sub  Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs)_
       Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
      End Sub#End Region  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
       Handles MyBase.Load
        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")
        mengxianhui.InnerText = "【孟宪会之精彩世界】- 将DataGrid输出到Excel文件"
        Me.BindDataGrid()
      End Sub  Private Sub BindDataGrid()
        cnn.Open()
        Dim reader As OleDbDataReader = sql.ExecuteReader()
        Me.DataGrid1.DataSource = reader
        Me.DataGrid1.DataBind()
        reader.Close()
        cnn.Close()
      End Sub  Private Sub WriteDataGrid2Excel()
        Dim xlsheet As New SpreadsheetClass()
        cnn.Open()
        Dim reader As OleDbDataReader = Me.sql.ExecuteReader()
        Dim numbercols As Integer = reader.FieldCount
        Dim row As Integer = 2
        Dim i As Integer = 0
        ' 输出标题
        For i = 0 To numbercols - 1
          xlsheet.ActiveSheet.Cells(1, i + 1) = reader.GetName(i).ToString()
        Next    ' 输出字段内容
        While (reader.Read())
          For i = 0 To numbercols - 1
            xlsheet.ActiveSheet.Cells(row, i + 1) = reader.GetValue(i).ToString()
          Next
          row = row + 1
        End While
        reader.Close()
        cnn.Close()
        Try
          xlsheet.ActiveSheet.Export(Server.MapPath(".") + "\Images\" + Me.xlfile.Text,_
           OWC.SheetExportActionEnum.ssExportActionNone)
        Catch e As System.Runtime.InteropServices.COMException
          Response.Write("错误:" + e.Message)
        End Try
      End Sub  Private Sub WriteDataGrid2Excel2()
        Dim xlsheet As New SpreadsheetClass()
        Dim i As Integer = 0
        Dim j As Integer = 0
        'Response.End()
        ' 输出标题
        Dim oItem As DataGridColumn
        For Each 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.Range(xlsheet.Cells(1, 1), xlsheet.Cells(1, i + 1)).Font.Bold = True
          xlsheet.Range(xlsheet.Cells(1, 1), xlsheet.Cells(1, i + 1)).Font.Color = "red"
          i = i + 1
        Next    Dim numbercols As Integer = DataGrid1.Items.Item(0).Cells.Count
        ' 输出字段内容
        For j = 0 To DataGrid1.Items.Count - 1
          For i = 0 To numbercols - 1
            xlsheet.Range(xlsheet.Cells(2, 2), xlsheet.Cells(j + 2, i + 1)).Font.Color = "blue"
            'xlsheet.Range("A2:B14").WrapText = True
            xlsheet.Range(xlsheet.Cells(2, 1), xlsheet.Cells(j + 2, i + 1)).AutoFitColumns()
            xlsheet.ActiveSheet.Cells(j + 2, i + 1) = DataGrid1.Items.Item(j).Cells(i).Text.Replace("&nbsp;", " ")
          Next
        Next
        Try
          xlsheet.ActiveSheet.Export(Server.MapPath(".") + "\Images\" + Me.xlfile.Text,_
           OWC.SheetExportActionEnum.ssExportActionNone)
        Catch e As System.Runtime.InteropServices.COMException
          Response.Write("错误:" + e.Message)
        End Try
      End Sub  Private Sub ExportDataGrid2Excel_Click(ByVal sender As Object,_
       ByVal e As System.EventArgs) Handles ExportDataGrid2Excel.Click
        If (Me.xlfile.Text.Trim() <> "") Then
          Me.WriteDataGrid2Excel2()
        End If
      End Sub  Private Sub ExportDataBase2Excel_Click(ByVal sender As Object, _
       ByVal e As System.EventArgs) Handles ExportDataBase2Excel.Click
        If (Me.xlfile.Text.Trim() <> "") Then
          Me.WriteDataGrid2Excel()
        End If
      End SubEnd Class
      

  5.   

    其实导出到excel有4种方法:
    第一种:http://www.cnblogs.com/unruledboy/archive/2004/07/07/22093.aspx
    第二种就是我的第一个问题,只不过暂时不知道怎么用
    第三种public class ExportToExcel
        {        私有成员#region 私有成员
            // 数据的DataView
            private DataView dv=null;        // 表格标题
            private string title=null;        // 输出文件路径
            private string outFilePath=null; 
            // 输入文件名
            private string inputFilePath=System.Windows.Forms.Application.StartupPath+@" emplate.xls";        #endregion        公共属性#region 公共属性
            /**//// <summary>
            /// 数据的DataView
            /// </summary>
            public DataView DV
            {
                set
                {
                    dv=value;
                }
            }        /**//// <summary>
            /// 表格标题
            /// </summary>
            public string Title
            {
                set
                {
                    title=value;
                }
                get
                {
                    return title;
                }
            }        /**//// <summary>
            /// 输出文件路径
            /// </summary>
            public string OutFilePath
            {
                set
                {
                    outFilePath=value;
                }
                get
                {
                    return outFilePath;
                }
            }        /**//// <summary>
            /// 输入文件路径
            /// </summary>
            private string InputFilePath
            {
                set
                {
                    inputFilePath=value;
                }
                get
                {
                    return inputFilePath;
                }
            }        #endregion               构造函数#region 构造函数        public ExportToExcel()
            {
            }//        public OutputExcel(DataView dv,string title)
    //        {
    //
    //        }        #endregion        公共方法#region 公共方法
            /**///
            public void CreateExcel()
            {
                int rowIndex=4;//行起始坐标
                int colIndex=1;//列起始坐标            ApplicationClass myApp=null;
                Workbook myBook=null;
                Worksheet mySheet=null;            //如果文件不存在,则将模板文件拷贝一份作为输出文件
                if(!File.Exists(outFilePath))
                {
                    File.Copy(inputFilePath,outFilePath,true);
                }            myApp= new ApplicationClass();
                myApp.Visible=false;
                object oMissiong=System.Reflection.Missing.Value;
                myApp.Workbooks.Open(outFilePath,oMissiong,oMissiong,oMissiong,oMissiong,
                    oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,oMissiong,
                    oMissiong,oMissiong,oMissiong);
                myBook=myApp.Workbooks[1];
                mySheet=(Worksheet)myBook.ActiveSheet;            //取得标题
                foreach(DataColumn col in dv.Table.Columns)
                {
                    colIndex++;
                    mySheet.Cells[4,colIndex] = col.ColumnName;
                    mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置标题格式为居中对齐
                }            //取得表格中的数据
                foreach(DataRowView row in dv)
                {
                    rowIndex ++;
                    colIndex = 1;
                    foreach(DataColumn col in dv.Table.Columns)
                    {
                        colIndex ++;
                        if(col.DataType == System.Type.GetType("System.DateTime"))
                        {
                            mySheet.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
                            mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置日期型的字段格式为居中对齐
                        }
                        else  if(col.DataType == System.Type.GetType("System.String"))
                        {
                            mySheet.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
                            mySheet.get_Range(mySheet.Cells[rowIndex,colIndex],mySheet.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//设置字符型的字段格式为居中对齐
                        }
                        else
                        {
                            mySheet.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
                        }
                    }
                }            //加载一个合计行
                int rowSum = rowIndex + 1;
                int colSum = 2;
                mySheet.Cells[rowSum,2] = "合计";
                mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;            //设置选中的部分的颜色
                mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Select();
                mySheet.get_Range(mySheet.Cells[rowSum,colSum],mySheet.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//设置为浅黄色,共计有56种            //取得整个报表的标题
                mySheet.Cells[2,2] = title;            //设置整个报表的标题格式
                mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Bold = true;
                mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,2]).Font.Size = 22;            //设置报表表格为最适应宽度
                mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Select();
                mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Columns.AutoFit();            //设置整个报表的标题为跨列居中
                mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).Select();
                mySheet.get_Range(mySheet.Cells[2,2],mySheet.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;            //绘制边框
                mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
                mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//设置左边线加粗
                mySheet.get_Range(mySheet.Cells[4,2],mySheet.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗
                mySheet.get_Range(mySheet.Cells[4,colIndex],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗
                mySheet.get_Range(mySheet.Cells[rowSum,2],mySheet.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗
                myBook.Save();
                myBook.Close( true,outFilePath,true);            System.Runtime.InteropServices.Marshal.ReleaseComObject(mySheet);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(myApp);            myApp.Quit();
                GC.Collect();
            }
            #endregion        
        }
      

  6.   

    第四种:
    第四种:
    public void ExportToExcel(string pstrSql)
            {
                Excel.Application pApplication;
                Excel._Workbook xBk;
                Excel._Worksheet xSt;
                Excel._QueryTable xQt;
                string ExcelConn = "ODBC;DRIVER=SQL Server;SERVER=localhost;UID=sa;PWD=;APP=Microsoft(R) Windows (R) 2000 Operating System;WSID=me;DATABASE=pubs";
                pApplication = new Excel.ApplicationClass();
                xBk = pApplication.Workbooks.Add(true);
                xSt = (Excel._Worksheet)xBk.ActiveSheet;
                pApplication.Cells[2,2] = this.title;            xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Bold = true;
                xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Name = "黑体";
                xSt.get_Range(pApplication.Cells[2,2],pApplication.Cells[2,2]).Font.Size = 22;
                xQt = xSt.QueryTables.Add(ExcelConn,xSt.get_Range(pApplication.Cells[4,2],pApplication.Cells[4,2]),pstrSql);
                xQt.Name = "导出EXCEL";
                xQt.FieldNames = true;
                xQt.RowNumbers = false;
                xQt.FillAdjacentFormulas = false;
                xQt.PreserveFormatting = false;
                xQt.BackgroundQuery = true;
                xQt.RefreshStyle = Excel.XlCellInsertionMode.xlInsertDeleteCells;
                xQt.AdjustColumnWidth = true;
                xQt.RefreshPeriod = 0;
                xQt.PreserveColumnInfo = true;
                xQt.Refresh(xQt.BackgroundQuery);
                pApplication.Visible = true;
            }大家一起来学习讨论吧……
      

  7.   

    一个奇怪的事情:我把代码改成这样
    public void ExportToExcel(object sender,System.EventArgs e) 
            { 
                bool CurrCtlVisible=ctl.Visible;
                ctl.Visible=true;        Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");  
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.ContentType = "application/ms-excel"; 
                ctl.Page.EnableViewState = false; 
                System.IO.StringWriter tw = new System.IO.StringWriter(); 
                System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw); 
                ctl.RenderControl(hw); 
                Response.Write(tw.ToString()); 
                Response.End(); 
                
                ctl.Page.EnableViewState = true; 
                ctl.Visible=CurrCtlVisible;
            }然后用asp:button的onclick事件调用它,如果ctl这个datagrid是一页的话,没问题,可以正常引出,但是如果该datagrid有两页以上的话,会出现如下提示:
    类型“DataGridLinkButton”的控件“dgEmps1__ctl16__ctl1”必须放在具有 runat=server 的窗体标记内这是为什么?