今天网上找了N久基本全部是那个ASP.NET 里面的GRIDVIEW 变EXCEL, 基本没看见说WINFORM里面导出的,很是纳闷,现在特地在此送分给那位兄弟姐妹有方法介绍个小弟我看,,,坚决抵制那些在网上搜索到的ASP.NET帖给我...请注意噢,是C# WINDOW FORM里面的GRIDVIEW 不是网页的

解决方案 »

  1.   

      我的可以,我是用03的DataGrid 在05里应该可以用
    private void button3_Click(object sender, System.EventArgs e)
    {//导出excel
    //导出execl
    if(ds!=null)
    {
    doExport(ds,"未知名文档!");
    }
    else
    {
    MessageBox.Show("导出内容不能为空!","警告!",MessageBoxButtons.OK,MessageBoxIcon.Stop);
    }
    }
    private void doExport(DataSet ds,string strExcelFileName)   
    {  //导出execl
    try
    {                            
    Excel.Application excel= new Excel.Application();                            
    int rowIndex=1;   
    int colIndex=0;     
    excel.Application.Workbooks.Add(true);                              
                
    System.Data.DataTable table=ds.Tables[0]   ;   
    foreach(DataColumn col in table.Columns)   
    {   
    colIndex++;           
    excel.Cells[1,colIndex]=col.ColumnName;                                   
    }     
    foreach(DataRow row in table.Rows)   
    {   
    rowIndex++;   
    colIndex=0;   
    foreach(DataColumn col in table.Columns)   
    {   
    colIndex++;   
    excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();   
    }   
    }   
    excel.Visible=false;     
    excel.Save(strExcelFileName);   
    excel.Quit();   
    excel=null;   
    }
    catch(Exception ex)
    {
    MessageBox.Show(ex.Message,"警告!",MessageBoxButtons.OK,MessageBoxIcon.Stop);
    }                            
    GC.Collect();//垃圾回收   
    }
      

  2.   

    您可以说一下DataSet ds 这个DS 你是新定义的吗? 我的是那个DataSet 是我之前定义的,reportDataSet  我就拿这个reportDataSet 换一下你的DS是吗? 
      

  3.   

    因为我不能测试所以问题多点...我是导出我当前的GRIDVIEW里面的数据啊,不是到处那个DATASET所有数据. 看你的代码里面没有任何GRIDVIEW嘛?
      

  4.   

    public static void ExportGridView(GridView GridView1, string filename)
            {            string attachment = "attachment; filename=" + filename + ".xls";            HttpResponse Response = HttpContext.Current.Response;            Response.ClearContent();            Response.AddHeader("content-disposition", attachment);            Response.ContentType = "application/ms-excel";            StringWriter sw = new StringWriter();            HtmlTextWriter htw = new HtmlTextWriter(sw);
                // Create a form to contain the grid            HtmlForm frm = new HtmlForm();            GridView1.Parent.Controls.Add(frm);            frm.Attributes["runat"] = "server";            frm.Controls.Add(GridView1);
                frm.RenderControl(htw);            //GridView1.RenderControl(htw);            Response.Write(sw.ToString());            Response.End();        }