如何能够将dataGrid控件里面的数据导出到Excel?
数据库SqlServer2000
和dataGrid绑定的是SqlDataAdapter和DataSet
请大家踊跃发言。代码越详细越好

解决方案 »

  1.   

    最近刚好做过这个,呵呵,给搂住共享一下:Public Shared Function WriteCSVFile(ByVal in_filePath As String, ByVal in_dt As DataTable) As Boolean        Dim retFlg As Boolean = True
            Dim writeData As String
            Try
                ' Update Start 仕様変更4 - 20070716 by luopx
                'If Not in_dt Is Nothing And in_dt.Rows.Count > 0 Then
                If Not in_dt Is Nothing And in_dt.Rows.Count >= 0 Then
                    ' Update End 仕様変更4 - 20070716 by luopx
                    Dim myw As System.IO.StreamWriter = New System.IO.StreamWriter(in_filePath, False, System.Text.Encoding.GetEncoding("Shift-Jis"))
                    For cn As Integer = 0 To in_dt.Columns.Count - 1
                        If cn <> 0 Then
                            writeData += ","
                        End If
                        writeData += in_dt.Columns(cn).ColumnName()
                    Next
                    For i As Integer = 0 To in_dt.Rows.Count - 1
                        writeData += ControlChars.CrLf
                        Dim dataRow As dataRow = in_dt.Rows(i)
                        For j As Integer = 0 To dataRow.ItemArray.Length - 1
                            If j <> 0 Then
                                writeData += ","
                            End If
                            ' Update Start 仕様変更 - 20071025 by luopx
                            'writeData += CStr(dataRow.ItemArray(j))
                            If IsDBNull(dataRow.ItemArray(j)) Then
                                writeData += ""
                            Else
                                writeData += CStr(dataRow.ItemArray(j))
                            End If
                            ' Update Start 仕様変更 - 20071025 by luopx
                        Next
                    Next
                    myw.Write(writeData)
                    myw.Close()
                Else
                    HCLogger.WriteLog(HCLogger.LogLevel.WARN, " (HCCSVFileObject.WriteCSVFile)データテーブルにデータがない ")
                End If
            Catch ex As Exception
                ' エラーログ出力
                HCLogger.WriteLog(HCLogger.LogLevel.ERR, " (HCCSVFileObject.WriteCSVFile)CSVファイル書き込みエラー発生 ")
                retFlg = False
            End Try        Return retFlg    End Function
      

  2.   

    sqlserver2K 就有这个功能  "数据导出"
      

  3.   

    SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]); 
       SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn); 
       DataSet ds=new DataSet(); 
       da.Fill(ds,"table1"); 
       DataTable dt=ds.Tables["table1"]; 
       StringWriter sw=new StringWriter(); 
       sw.WriteLine("自动编号,姓名,年龄"); 
       foreach(DataRow dr in dt.Rows) 
       { 
        sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]); 
       } 
       sw.Close(); 
       Response.AddHeader("Content-Disposition", "attachment; filename=test.csv"); 
       Response.ContentType = "application/ms-excel"; 
       Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312"); 
       Response.Write(sw); 
       Response.End(); 
      

  4.   

    Response.Clear(); 
       Response.Buffer= false; 
       Response.Charset="GB2312"; 
       Response.AppendHeader("Content-Disposition","attachment;filename=test.xls"); 
       Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");    Response.ContentType = "application/ms-excel";    this.EnableViewState = false; 
       System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
       System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
       this.DataGrid1.RenderControl(oHtmlTextWriter); 
       Response.Write(oStringWriter.ToString()); 
       Response.End(); 
      

  5.   

    - -
    那个2楼的好心人...我说的是C#...不是VB...
      

  6.   

    Response?
    这个好像是web上用的吧?
    有没有C/S模式的
      

  7.   

    public bool ExportExcel()
            {
                return ExportExcel("");
            }
            public bool ExportExcel(string p_ReportName)
            {
                if ( this.TableStyles.Count == 0 ) return false;
                DataGridTableStyle ts = this.TableStyles[0];            // 创建表头                    --LeeWenjie    2006-11-21
                Excel.Application xlApp = new Excel.ApplicationClass();
                Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
                Excel.Worksheet xlSheet = (Excel.Worksheet)xlBook.Worksheets[1];
                
                Excel.Range range = xlSheet.get_Range(xlApp.Cells[1,1],xlApp.Cells[1,ts.GridColumnStyles.Count]);
                range.MergeCells = true;
                xlApp.ActiveCell.FormulaR1C1 = p_ReportName;
                xlApp.ActiveCell.Font.Size = 20;
                xlApp.ActiveCell.Font.Bold = true;
                xlApp.ActiveCell.HorizontalAlignment = Excel.Constants.xlCenter;            // 创建列头                    --LeeWenjie 2006-11-21
                int colIndex = 0;
                int RowIndex = 2;
                
                foreach(DataGridColumnStyle cs in ts.GridColumnStyles)
                {
                    colIndex++;
                    xlSheet.Cells[RowIndex,colIndex] = cs.HeaderText;
                }
                // 根据Grid显示的内容输出自Excel
                // 赋值给单元格
                int RowCount = this.BindingContext[this.DataSource,this.DataMember].Count;
                for(int i = 0 ; i < RowCount ;i++)
                {
                    RowIndex++;
                    int ColCount = ts.GridColumnStyles.Count;
                    for(colIndex = 1; colIndex <= ColCount ;colIndex++)
                    {
                        xlSheet.Cells[RowIndex,colIndex] = this[i,colIndex-1];
                    }
                    Application.DoEvents();
                }
                
                xlBook.Saved  = true;
                xlBook.SaveCopyAs("D:\\Fly" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
                xlApp.Quit();
                GC.Collect();
                return true;
            }
      

  8.   

    /// <summary>
    /// 导出dataGrid 中的数据
    /// </summary>
    /// <param name="exportobject">导出数据的对象,可以是Datagrid,或page</param>
    /// <param name="attachName">文件名称</param>
    /// <param name="exportTypeId">1:excel;2:word;3:txt;4:html</param>
    public void ExportDataGridData(Control[] control,string fileName,int exportTypeId)
    {
    Response.Clear(); 
    Response.Buffer= true; 
    Response.Charset="utf-8";
    string headerValue = "attachment;" + fileName + "=";//.xls"

    Response.ContentEncoding=System.Text.Encoding.GetEncoding("utf-8");
    //Response.ContentType指定文件类型 可以为application/ms-excel || application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档
    if(exportTypeId == 1)
    {
    headerValue += ".xls";
    Response.ContentType = "application/vnd.ms-excel";
    }
    else if(exportTypeId == 2)
    {
    headerValue += ".doc";
    Response.ContentType = "application/vnd.ms-word";
    }
    else if(exportTypeId == 3)
    {
    headerValue += ".txt";
    Response.ContentType = "application/vnd.ms-txt";
    }
    else if(exportTypeId == 4)
    {
    headerValue += ".html";
    Response.ContentType = "application/vnd.ms-html";
    }
    else
    {
    headerValue += ".xls";
    Response.ContentType = "application/vnd.ms-excel";
    }
    Response.AppendHeader("Content-Disposition",headerValue);
    Response.Charset = ""; //关闭 ViewState
    EnableViewState = false;
    System.IO.StringWriter tw = new System.IO.StringWriter();//将信息写入字符串
    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);//在WEB窗体页上写出一系列连续的HTML特定字符和文本。
    //此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
    //获取control的HTML
    foreach(Control con in control)
    {
    if(con != null)
    {
    if(con is DataGrid)
    {
    if(((DataGrid)con).Items.Count > 0)
    {
    con.RenderControl(hw);//将DATAGRID中的内容输出到HtmlTextWriter对象中
    }
    }
    else
    {
    con.RenderControl(hw);
    }
    }
    }
    // 把HTML写回浏览器
    Response.Write(tw.ToString());
    Response.End();
    }
      

  9.   

    一个都不行啊
    现在就一个*.cs的类
    别把东西写那么复杂。就一个fomr界面而已。
      

  10.   

    搞定了。
    原来忘了应用com的excel