c#开发了一个从数据库查询的界面,现在需要加个按钮,按钮功能需要为导出.导出功能..

解决方案 »

  1.   

    private void button5_Click_1(object sender, EventArgs e) 
            { 
                //建立Excel对象 
                Excel.Application excel = new Excel.Application(); 
                excel.Application.Workbooks.Add(true); 
                //生成字段名称 
                for (int i = 0; i < dataGridView2.ColumnCount; i++) 
                { 
                    excel.Cells[1,i + 1] = dataGridView2.Columns[i].HeaderText; 
                    if (y == 0) 
                    { 
                        y = 1; 
                        toolStripStatusLabel6.Text = "数据导入中,请等待!"; 
                    } 
                } 
                //填充数据 
                for (int i = 0; i < dataGridView2.RowCount - 1; i++) 
                { 
                    for (int j = 0; j < dataGridView2.ColumnCount; j++) 
                    { 
                        if (dataGridView2[j, i].Value == typeof(string)) 
                        { 
                            excel.Cells[i + 2, j + 1] = "" + dataGridView2[i, j].Value.ToString(); 
                        } 
                        else 
                        { 
                            excel.Cells[i + 2, j + 1] = dataGridView2[j, i].Value.ToString(); 
                        } 
                    } 
                } 
    excel.Visible = true; 
            } 
      

  2.   

     toolStripStatusLabel6这个没啊.....
      

  3.   

    1//注意引入IO空间
     using System.IO;
     
    2 (1)在源代码<page>里中加入:EnableEventValidation = "false" 
      (2) public void ExcelOut(GridView gv)
        {//导出Excel表的方法
            if (gv.Rows.Count > 0)
            {//有数据行
                Response.Clear();
                Response.ClearContent();
                Response.AddHeader("Content-Disposition","attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//以系统时间设置为文件名
                Response.ContentEncoding = System.Text.Encoding.UTF8;//UTF8编码
                Response.ContentType = "application/ms-excel";//文件类型
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                gv.RenderControl(htw);
                Response.Write(sw.ToString());
                Response.Flush();
                Response.End();//结束
            }
            else
            {
               Response.Write("没有数据记录");
            }
        }
        protected void Button1_Click(object sender, EventArgs e)
        {//导出按钮事件
            ExcelOut(GridView1);//调用方法
        }
        public override void VerifyRenderingInServerForm(Control control)//必须有这个方法
        {    }