2

次のコードを使用して、データセットをExcelシートにエクスポートしています。

[WebMethod]
    public static void ExporttoExcel()
    {
        DataSet ds;
       productfactory pf=new productfactory();
        ds = pf.getproducts();
        HttpResponse response = HttpContext.Current.Response;

        // first let's clean up the response.object
        response.Clear();
        response.Charset = "";
        response.ContentEncoding = System.Text.Encoding.Default;

        // set the response mime type for excel
        response.ContentType = "application/vnd.ms-excel";
        response.AddHeader("Content-Disposition", "attachment;filename=\"products.xls\"");

        // create a string writer
        using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                // instantiate a datagrid
                DataGrid dg = new DataGrid();                    
                dg.DataSource = ds.Tables[0];
                dg.DataBind();
                dg.RenderControl(htw);
                string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\products.xls";                    
                response.Write(sw.ToString());
               // response.End();

            }
        }       
    }

問題は、ファイルのダウンロードが発生しないため、エクスポートが行われないことです。同じコードが通常の方法で正常に機能します。しかし、Webメソッドでは機能しません。

4

3 に答える 3

2

ashxで終わるHttpHandlerを作成し、Excelファイルを作成するコードをその中に配置することをお勧めします。

次に、そのようなJavaScriptコードから呼び出します。

document.location.href = "ExporttoExcel.ashx";
于 2010-08-06T17:34:27.120 に答える
1

問題は、WebMethodsがResponseオブジェクトと対話できるように設計されていないことです(それが利用できず、それに到達するためにHttpContext.Current.Responseを使用する必要があったことは明らかです)。WebMethodsは、ユーザーにとってブラックボックスになるように設計されています。彼らは実行し、行動し、そして/または値を返します。

おそらく、あなたはあなたが達成しようとしていることについてより良い考えを私たちに与えることができ、私たちは別の解決策を提案することができます。

于 2010-08-06T18:02:26.800 に答える
-1

uを使用してURLをWebハンドラーに設定した動的iframeを作成し、Excelを生成できます。これにより、現在のページを投稿せずにファイルのダウンロードが発生します。

于 2011-01-16T09:06:33.927 に答える