2016-11-24 78 views
0

我有一個asp.net應用程序,其中有一個js文件和一個ashx文件。在這裏,在下載按鈕單擊林調用Ajax調用處理程序文件,並在JSON格式的字符串/數據表檢索SQL表數據和進出口試圖JSON格式化字符串/數據表導出到的Excel/CSV文件和下載它。請幫我找到一個解決方案。 (需要一個幫助導出大量數據和下載的解決方案)批量數據導出爲ex​​cel並在ashx文件中下載

我試過下面的代碼,但它沒有下載excel文件。

public void ProcessRequest(HttpContext context) 
     { 
      context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls"); 
      context.Response.ContentType = "application/csv"; 
      HttpResponse response = context.Response; 
      string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');    
      response.Write(exportContent); 
      context.Response.End(); 
     } 

public DataTable JsonStringToDataTable(string jsonString) 
     { 
      DataTable dt = new DataTable(); 
      string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{"); 
      List<string> ColumnsName = new List<string>(); 
      foreach (string jSA in jsonStringArray) 
      { 
       string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ","); 
       foreach (string ColumnsNameData in jsonStringData) 
       { 
        try 
        { 
         int idx = ColumnsNameData.IndexOf(":"); 
         string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", ""); 
         if (!ColumnsName.Contains(ColumnsNameString)) 
         { 
          ColumnsName.Add(ColumnsNameString); 
         } 
        } 
        catch (Exception ex) 
        { 
         //throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData)); 
         throw ex; 
        } 
       } 
       break; 
      } 
      foreach (string AddColumnName in ColumnsName) 
      { 
       dt.Columns.Add(AddColumnName); 
      } 
      foreach (string jSA in jsonStringArray) 
      { 
       string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ","); 
       DataRow nr = dt.NewRow(); 
       foreach (string rowData in RowData) 
       { 
        try 
        { 
         int idx = rowData.IndexOf(":"); 
         string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", ""); 
         string RowDataString = rowData.Substring(idx + 1).Replace("\"", ""); 
         nr[RowColumns] = RowDataString; 
        } 
        catch (Exception ex) 
        { 
         continue; 
        } 
       } 
       dt.Rows.Add(nr); 
      } 
      return dt; 
     } 


private static string GetDataFromTable() 
     { 
      string returnValue = string.Empty; 
      var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue }; 
      try 
      { 
       var result = //get data from sql table; 
       returnValue = serializer.Serialize(result); 
      } 
      catch (Exception e) 
      { 
       returnValue = serializer.Serialize(e.Message); 
      } 
      return returnValue; 
     } 


public string ExportToSpreadsheet(DataTable table, string name) 
      { 
       string res = string.Empty; 
       try 
       { 
        //var resp = Response; 
        System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response; 
        resp.Clear(); 
        if (table != null) 
        { 
         foreach (DataColumn column in table.Columns) 
         { 
          resp.Write(column.ColumnName + ","); 
         } 
        } 

        resp.Write(Environment.NewLine); 
        if (table != null) 
        { 
         foreach (DataRow row in table.Rows) 
         { 
          for (int i = 0; i < table.Columns.Count; i++) 
          { 
           resp.Write(row[i].ToString().Replace(",", string.Empty) + ","); 
          } 

          resp.Write(Environment.NewLine); 
         } 
        } 

        res = "successfully downloaded"; 
        resp.ContentType = "text/csv"; 
        resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");     
        // resp.End(); 

       } 
       catch(Exception ex) 
       { 
        res = ex.Message; 
       } 
       return res; 
      } 
+0

爲什麼SQL標籤?我看不到任何SQL ... – jarlh

+0

GetDataFromTable()在此函數中從sql中檢索數據 – Sudha

+0

請參閱http://stackoverflow.com/questions/12087040/file-download-by-calling-ashx-page?rq=1 – Serg

回答

0

開始使用像EPPlus這樣的專門文庫。它會創建真正的Excel文件。

private void exportToExcel(DataTable dataTable) 
{ 
    using (ExcelPackage excelPackage = new ExcelPackage()) 
    { 
     //create the worksheet 
     ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1"); 

     //load the datatable into the sheet, with headers 
     worksheet.Cells["A1"].LoadFromDataTable(dataTable, true); 

     //send the file to the browser 
     byte[] bin = excelPackage.GetAsByteArray(); 
     Response.ClearHeaders(); 
     Response.Clear(); 
     Response.Buffer = true; 
     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
     Response.AddHeader("content-length", bin.Length.ToString()); 
     Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\""); 
     Response.OutputStream.Write(bin, 0, bin.Length); 
     Response.Flush(); 
     HttpContext.Current.ApplicationInstance.CompleteRequest(); 
    } 
}