2010-11-18 1 views
4

私はHTMLテーブルからデータを取得するため、クライアント側で、次のコードを持っているし、ページメソッドを介してサーバに送信:エクスポートHTML表

function dtExportToCSV(dataTable) { 
    var elements = dtDataToJSON(dataTable); 
    var headers = dtHeadersToJSON(tableSelector); 

    jQuery.ajax({ 
     type: "POST", 
     url: "Report.aspx/exportToCSV", 
     data: "{'elements': " + elements + ", 'headers': " + JSON.stringify(headers) + "}", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 

     success: function(msg) { 
      if (msg.d) { 
      } else { 
      } 
     }, 

     error: function(xhr, ajaxOptions, thrownError) { 
      alert(xhr.statusText); 
     } 
    }); 
} 

その後、私は使用して取得したデータをCSVファイルにエクスポートするには、サーバー側の次のコードを使用します。

/// <summary> 
/// 
/// </summary> 
/// <param name="elements"></param> 
/// <param name="headers"></param> 
[WebMethod(EnableSession=true)] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public static bool exportToCSV(List<object> elements, List<string> headers) 
{ 
    try 
    { 
     string attachmentType = "attachment; filename=ShortageReport.csv"; 

     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.ClearHeaders(); 
     HttpContext.Current.Response.ClearContent(); 
     HttpContext.Current.Response.AddHeader("content-disposition", attachmentType); 
     HttpContext.Current.Response.ContentType = "text/csv"; 
     HttpContext.Current.Response.AddHeader("Pragma", "public"); 

     writeHeadersInfo(headers); 

     HttpContext.Current.Response.End(); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 

    return false; 
} 

しかし、私はこのexpcetion取得:コードが最適化またはネイティブフレームがコールスタックの一番上にあるされているため、式を評価することができませんを。

誰もこの問題を処理する方法を知っていますか?

ご協力いただければ幸いです。 ありがとうございました!

〜エダーキノン

+0

例外はどの回線から来ましたか? – Ender

答えて

1

私はLeonが答えとして提案したことをしましたが、代わりに汎用ハンドラを使用しました。

1.-サーバー(メインページ)にデータを送信するJSON &を構築し、クライアントからデータを取得します。

function dtExportToCSV(dataTable) { 
     var elements = dtDataToJSON(dataTable); 
     var headers = dtHeadersToJSON(tableSelector); 

     jQuery.ajax({ 
      type: "POST", 
      url: "ashx/Export.ashx", 
      data: "{'elements': " + elements + ", 'headers': " + headers + "}", 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 

      success: function(msg) { 
       window.open("Export.aspx", "Export CSV", "width=120,height=300"); 
      }, 

      error: function(xhr, ajaxOptions, thrownError) { 
       alert(xhr); 
      } 
     }); 

     return false; 
    } 

2.-を介して、データ間の交換のため(のStringBuilderなど)セッション変数の初期化ASPXページ(メインページ):

protected void Page_Load(object sender, EventArgs e) 
    { 
     if (Session["ExportCSV"] == null) 
     { 
      Session["ExportCSV"] = new StringBuilder(); 
     } 

     if (!IsPostBack) 
     { 

     } 

    } 

3.- CSV(ジェネリックハンドラ)をビルドします。

public class Export : IHttpHandler, IRequiresSessionState 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     object json = null; 
     byte[] input = null; 

     JavaScriptSerializer javascriptSerializer = null; 
     StringBuilder sb = null; 

     List<object> elementList = null; 
     List<string> headerList = null; 

     try 
     { 
      input = readToEnd(context.Request.InputStream); 
      sb = new StringBuilder(); 
      javascriptSerializer = new JavaScriptSerializer(); 

      foreach (byte chr in input) 
      { 
       sb.Append((char)chr); 
      } 

      json = javascriptSerializer.DeserializeObject(sb.ToString()); 

      elementList = new List<object>(); 
      headerList = new List<string>(); 

      var dictionary = json.toType(new Dictionary<string, object>()); 
      foreach (KeyValuePair<string, object> keyValuePair in dictionary) 
      { 
       switch (keyValuePair.Key) 
       { 
        case "elements": 
        case "ELEMENTS": 
         { 
          object[] elements = (object[])keyValuePair.Value; 
          foreach (object element in elements) 
          { 
           elementList.Add(element); 
          } 
          break; 
         } 

        case "headers": 
        case "HEADERS": 
         { 
          object[] headers = (object[])keyValuePair.Value; 
          foreach (object header in headers) 
          { 
           headerList.Add((string)header); 
          } 

          break; 
         } 
       } 
      } 

      ((StringBuilder) context.Session["ExportCSV"]).Append(writeBodyInfo(elementList, headerList)); 
      ((StringBuilder) context.Session["ExportCSV"]).Append(writeHeadersInfo(headerList)); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
      throw; 
     } 
    } 
} 

4.-保存ファイルダイアログ(Export.aspx)を表示:

public partial class Export : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      exportToCSV(); 
     } 
    } 

    private void exportToCSV() 
    { 
     Context.Response.Clear(); 
     Context.Response.ClearContent(); 
     Context.Response.ClearHeaders(); 

     Context.Response.AddHeader("Content-Disposition", "attachment;filename=ShortageReport.csv"); 
     Context.Response.ContentType = "text/csv"; 

     char[] separator = Environment.NewLine.ToCharArray(); 
     string csv = ((StringBuilder)Session["ExportCSV"]).ToString(); 

     foreach (string line in csv.Split(separator)) 
     { 
      Context.Response.Write(line); 
     } 

     Context.Response.Flush(); 
     Context.Response.End(); 
    } 
} 

どれ改善、提案を?

〜EderQuiñones

1
/// <summary> 
    /// 
    /// </summary> 
    /// <param name="elements"></param> 
    /// <param name="headers"></param> 
    [WebMethod(EnableSession=true)] 
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
    public static bool exportToCSV(List<object> elements, List<string> headers) 
    { 
     try 
     { 
      string attachmentType = "attachment; filename=Shortage Report.csv"; 

      HttpContext.Current.Response.Clear(); 
      HttpContext.Current.Response.ClearContent(); 
      HttpContext.Current.Response.ClearHeaders(); 

      HttpContext.Current.Response.AddHeader("Content-Disposition", attachmentType); 
      HttpContext.Current.Response.ContentType = "text/csv"; 

      writeHeadersInfo(headers); 
      writeBodyInfo(headers, elements); 

      HttpContext.Current.ApplicationInstance.CompleteRequest(); 
     } 
     catch (Exception ex) 
     { 
      Console.WriteLine(ex.Message); 
     } 

     return true; 
    } 

しかし、それはセーブファイルダイアログを表示されません...

1

ない正確にAJAXが、私はどの個別のASPXページを構築することにより、前にこの機能を実現しましたCSVファイルを生成します(すでにexportToCSV()で行っています)。

クライアントページでは、JSを使用して、style="display:none"というスタイリングの動的に挿入されたiframeにこのASPXページを読み込みます。

ページにiframeを含めて、必要に応じてJSを使用して「エクスポート」ページを読み込むこともできます。

編集: PageMethodコールを使用してサーバーにテーブルを送信し、CSVを生成してSession []に格納することができます。次に、ページに戻って、上記の「エクスポート」ページを読み込んで、セッションに保存されているこのCSVを取得します。

関連する問題