同上,谢谢!!!

解决方案 »

  1.   

    //把table控件中的数据保存到excel或word
      public void Save(System.Web.UI.Control source, DocumentType type) 
      {
       Response.Clear(); 
       Response.Buffer= true;    //设置Http的头信息,编码格式
       if (type == DocumentType.Excel)
       {
        //Excel
        Response.AppendHeader("Content-Disposition","attachment;filename=result.xls");
        Response.ContentType = "application/ms-excel";
       }
       else if (type == DocumentType.Word)
       {
        //Word
        Response.AppendHeader("Content-Disposition","attachment;filename=result.doc");
        Response.ContentType = "application/ms-word";
       }   //设置编码
       Response.Charset="GB2312";  
       Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");   //关闭控件的视图状态
       source.EnableViewState =false;      //初始化HtmlWriter
       System.IO.StringWriter writer = new System.IO.StringWriter() ;
       System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
       source.RenderControl(htmlWriter);   //输出
       Response.Write(writer.ToString());   Response.End();
      }
       //以下是保存图片
       public void SavePic()
      {
       string path = Server.MapPath(".") + @"\images\Chart.jpeg";
       FileStream file = File.OpenRead(path);
       byte[] content = new byte[file.Length];
       file.Read(content,0,content.Length);
       file.Close();   Response.Clear(); 
       Response.AppendHeader("Content-Disposition","attachment;filename=Chart.jpeg");
       Response.ContentType = "image/jpeg";//设置Http的头信息
       Response.BinaryWrite(content);//输出
       
       Response.End();
      }
      

  2.   

    DataGrid的数据导出Excel
    #region 导出并下载
            /// <summary>
            /// 方法编号:14
            /// 方法名称:ExportExcel
            /// 内容摘要:将DataGrid中的数据导出到指定的Excel文件中
            /// </summary>
            /// <param name="page">Web页面对象</param>
            /// <param name="dataGrid">包含被导出数据的DataGrid对象</param>
            /// <param name="FileName">Excel文件的名称</param>
            /// <param name="strTitle">导出Excel文件的标题</param>
            /// <param name="iColspan">指定dataGrid的列数</param>
            public static void ExportExcel(System.Web.UI.Page page,System.Web.UI.WebControls.DataGrid dataGrid,
                string FileName,string strTitle,int iColspan)
            {
                System.Web.HttpResponse httpResponse = page.Response;
                
                httpResponse.AppendHeader("Content-Disposition","attachment;filename=" 
                    + HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8));             httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
                httpResponse.ContentType ="application/ms-excel";            System.IO.StringWriter  tw = new System.IO.StringWriter() ;
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);            //设置导出的Excel文件中的字体属性
                hw.AddAttribute("style","FONT-FAMILY: 宋体;FONT-SIZE: 10pt");            //将DataGrid中的内容输入到hw对象中
                dataGrid.RenderControl(hw);             //在服务器上创建文件的路径和文件名
                string filePath = System.Web.HttpContext.Current.Server.MapPath("../Doc/") + FileName;
                System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
                
                //写文件
                //写入文件标题
                sw.WriteLine("<table><tr><td align='center' colspan='" + iColspan + "'><font face='宋体' size=12px><b>" 
                    + strTitle + "</b></font></td></tr>");
                
                //写入制表时间
                sw.WriteLine("<tr><td colspan='" + iColspan + "' align='right'><font face='宋体' size=10px>制表时间:"
                    + DateTime.Now.ToString("yyyy年MM月dd日") + "</font></td></tr></table>");
                sw.Write(tw.ToString());
                sw.Close();            //下载文件
                DownFile(httpResponse,FileName,filePath);

                httpResponse.End();
            }
      

  3.   

    下载
    /// <summary>
            /// 方法编号:16
            /// 方法名称:DownFile
            /// 内容摘要:提示用户导出的文件是打开还是保存
            /// </summary>
            /// <param name="Response">输出流对象</param>
            /// <param name="fileName">下载的默认文件名</param>
            /// <param name="fullPath">文件的全路径包括文件名</param>
            private static bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
            {
                try
                {
                    Response.ContentType = "application/octet-stream";

                    Response.AppendHeader("Content-Disposition","attachment;filename=" + 
                        HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8) + ";charset=GB2312");
                    System.IO.FileStream fs= System.IO.File.OpenRead(fullPath);
                    long fLen=fs.Length;                //每100K同时下载数据 
                    int size=102400;                //指定缓冲区的大小
                    byte[] readData = new byte[size];                 //如果每次下载的数据大于文件的大小,改变下载数据大小为文件的大小
                    if(size > fLen)
                    {
                        size=Convert.ToInt32(fLen);
                    }                long fPos=0;
                    bool isEnd=false;                //读文件
                    while (!isEnd) 
                    { 
                        if((fPos+size)>fLen)
                        {
                            size=Convert.ToInt32(fLen-fPos);
                            readData = new byte[size];
                            isEnd=true;
                        }                    //读入一个压缩块 
                        fs.Read(readData, 0, size);
                        Response.BinaryWrite(readData);
                        fPos+=size;
                    } 
                    fs.Close(); 
                    
                    //将服务器上的文件删除
                    System.IO.File.Delete(fullPath);
                    return true;
                }
                catch
                {
                    return false;
                }
            }
      

  4.   

    to:WZCNet.虽然我不是楼主,还是要谢谢你.看你贴出来的代码,写得非常规范.,这些代码的重用性很高,可不可以将其它方法的代码也贴出来.方便大家共用.
    非常感谢.如果需要分的话,我可以另开贴聊表谢意!
      

  5.   

    TO:WZCNet(只有想不到,没有做不到)
      首先感谢您的帮助,我用了您的方法,在这一行的时候执行错误:dataGrid.RenderControl(hw); 
      错误消息:
      异常详细信息: System.Web.HttpException: 类型“DataGridLinkButton”的控件“dgCard__ctl2__ctl0”必须放在具有 runat=server 的窗体标记内。  另外,我想请问一下,我不只是想将datagrid的数据导出,能不能我将查询到的数据一条条写到hw中,因为datagrid有分页,不知道您的数据能不能将所有分页的数据都导出!还有就是,如果可以导出所有分面的数据,我在一个frame中,怎么导出另一个frame中的datagrid的数据呢?
    谢谢
      

  6.   

    参考: private object _optionalValue = System.Reflection.Missing.Value; private void ExportButton_Click( Object sender, EventArgs e )
    {
    Excel.Application excelApp;
    Excel.Workbook workBook;
    Excel.Worksheet worksheet;
    Excel.Range range; int row = 1;
    int cell = 1; try
    {
    excelApp = new Excel.Application();
    workBook = excelApp.Workbooks.Add( XlWBATemplate.xlWBATWorksheet );
    worksheet = ( Worksheet ) workBook.Worksheets[1];
    }
    catch( Exception exception )
    {
    Js.MessageBox( this.Page, exception.Message + "/r/n" + "An incompatible version of Microsoft Excel is intalled on your system." );
    return;
    } //Title
    worksheet.Name = "统计";
    worksheet.Cells[row, 1] = DateTime.Now.ToShortDateString();
    range = ( Range ) worksheet.Cells[row, 1];
    range.Font.Bold = true;
    row += 2; string [] headers = new string []{ "服务商", "产品名称", "服务", "订阅", "取消" };
    foreach( string header in headers )
    {
    worksheet.Cells[row, cell] = header;
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.Font.Bold = true;
    range.AutoFit();
    cell++;
    }
    cell = 1;
    row += 2; // create rows IList cps = Cps.GetContentProviders();
    foreach( ContentProviderInfo contentProvider in cps )
    {
    // int cpRegion = cell; 
    worksheet.Cells[row, cell] = contentProvider.ContentProviderName;
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.AutoFit();
    cell++;
    IList products = Products.GetProductsByCp( contentProvider.ContentProviderId, true );
    foreach( ProductFlowInfo product in products )
    {
    int productRegion = cell; 
    worksheet.Cells[row, cell] = product.ProductName;
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.AutoFit();
    cell++; IList services = Products.GetProductServices( product.ProductId );
    foreach( ProductServiceInfo service in services )
    {
    int serviceRegion = cell; 
    ServiceTypeInfo serviceType = Mobiles.GetServiceType( service.ServiceTypeId );
    worksheet.Cells[row, cell] = serviceType.ServiceTypeName + "(" + Products.GetFeeTypeText( service.FeeType ) + ")";
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.AutoFit();
    cell++; worksheet.Cells[row, cell] = Statistics.GetCpStatisticCount( Convert.ToInt32( service.ServiceId ), StatisticStatus.Subscribed, ( StatisticTimeType ) Convert.ToInt32( timeTypeDropDownList.SelectedItem.Value ), Convert.ToDateTime( calendar.Text != string.Empty ? calendar.Text : DateTime.Now.ToShortDateString() ), cityDropDownList.SelectedItem.Value );
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.AutoFit();
    cell++; worksheet.Cells[row, cell] = Statistics.GetCpStatisticCount( Convert.ToInt32( service.ServiceId ), StatisticStatus.UnSubscribe, ( StatisticTimeType ) Convert.ToInt32( timeTypeDropDownList.SelectedItem.Value ), Convert.ToDateTime( calendar.Text != string.Empty ? calendar.Text : DateTime.Now.ToShortDateString() ), cityDropDownList.SelectedItem.Value );
    range = ( Range ) worksheet.Columns[ cell, _optionalValue ];
    range.AutoFit(); row++;
    cell = serviceRegion;
    }
    row++;
    cell = productRegion;
    }
    row++;
    cell = 1;
    }
    row++; string fileName = DateTime.Now.ToShortDateString() + ".xls";
    string filePath = HttpContext.Current.Server.MapPath( fileName );
    workBook.SaveCopyAs( filePath );
    workBook.Close( false, null, null );
    excelApp.Workbooks.Close();
    excelApp.Quit();
    System.Runtime.InteropServices.Marshal.ReleaseComObject( range );
    System.Runtime.InteropServices.Marshal.ReleaseComObject( worksheet );
    System.Runtime.InteropServices.Marshal.ReleaseComObject( workBook );
    System.Runtime.InteropServices.Marshal.ReleaseComObject( excelApp );
    range = null;
    worksheet = null;
    workBook = null;
    excelApp = null;
    GC.Collect(); System.IO.FileStream fileStream = System.IO.File.OpenRead( filePath );
    byte[] fileData = new byte[ fileStream.Length ];
    fileStream.Read( fileData, 0, ( int ) fileStream.Length );
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader( "Content-Type", "application/vnd.ms-excel" );
    fileName = System.Web.HttpUtility.UrlEncode( System.Text.Encoding.UTF8.GetBytes( fileName ) );
    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename="+ System.Convert.ToChar(34) + fileName + System.Convert.ToChar(34) );
    HttpContext.Current.Response.AddHeader("Content-Length", fileStream.Length.ToString() );
    HttpContext.Current.Response.BinaryWrite( fileData );
    fileStream.Close();
    System.IO.File.Delete( filePath );
    HttpContext.Current.Response.End(); }
      

  7.   

    To:lzhzxl(云中人)这个导出Excel的原理是将DataGrid解释成一个HtmlTable的Html代码,等你导出来后你可以用记事本看一下Excel文件的内容,全是Html代码。是Html代码所以其中就不能包括服务器控件,我看你的错误是因为你启用了分页功能,所有提示这个错误。这点是没有关系的,你在导出按钮里加一点点处理就可以了。
    DataGrid.AllowPaging = false;然后再调用绑定的方法重新绑定一次后再导出就可以了,这样的话,就将数据源中的所有数据都导出来了,这样不是更好吗?再提醒一点,或者当你在用模板列时,当模板列中加了一个Button时,在导出时也要处理一下,DataGrid.Columns[8].Visible = false;
    这样就不会有错误了。以上的这些并不会改变DataGrid的样式,只是对导出来的数据产生变化。
    这个方法的好处是可以保持DataGrid的原样式,并且速度还快。你所说的导出另一个frame的问题也可以的,只要能访问到这个DataGrid并且按照我上边所提示的处理一下就可以了。
      

  8.   

    刚刚在用,参考一下:
    #region 将DataTable中数据导出到EXCEL中
    /// <summary>
    /// 将DataTable中数据导出到EXCEL中
    /// </summary>
    /// <returns>返加明文字符串</returns>

    public static void  ExportExcel(DataTable dataTable,Page page)
    {
    HttpResponse resp;
    resp = page.Response;
    resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
    resp.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
    string colHeaders= "", ls_item="";
    int i=0;
    DataRow[] myRow=dataTable.Select(""); 
    for(i=0;i<dataTable.Columns.Count-1;i++)
    {
    colHeaders+=dataTable.Columns[i].Caption.ToString()+"\t";
    }
    colHeaders +=dataTable.Columns[i].Caption.ToString() +"\n";
    //向HTTP输出流中写入取得的数据信息(表头信息)
    resp.Write(colHeaders);
    //逐行处理数据
    foreach(DataRow row in myRow)
    {
    //在当前行中,逐列获得数据,数据之间以\t分割,结束时加回车符\n
    for(i=0;i<row.Table.Columns.Count-1;i++)
    ls_item +=row[i].ToString() + "\t";
    ls_item += row[i].ToString() +"\n";
    //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
    resp.Write(ls_item);
    ls_item="";
    }
    resp.End();
    }
    #endregion
      

  9.   

    谢谢大家的帮助,特别感谢WZCNet(只有想不到,没有做不到) ,50分不够,我再加50来给大家,谢谢!!