2008-11-07 11 views
1

quelle est la meilleure façon d'exporter un Datagrid pour exceller? Je n'ai aucune expérience dans l'exportation de DataGrid pour exceller, alors je veux savoir comment vous exportez DataGrid pour exceller. Je l'ai lu il y a beaucoup de façons, mais je pense simplement faire une simple exportation Excel pour DataGrid function.i je utilise asp.net C#export Datagrid pour exceler asp

acclamations ..

Répondre

6

La façon la plus simple est de simplement écrire soit csv, ou html (en particulier, un <table><tr><td>...</td></tr>...</table>) à la sortie, et simplement prétendre qu'il est au format Excel via l'en-tête de type de contenu. Excel se chargera heureusement soit; csv est plus simple ...

Voici un exemple similaire (il faut en fait un IEnumerable, mais il serait similaire de toute source (comme un DataTable, en boucle sur les lignes).

 public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename) 
     { 
      if (data == null) throw new ArgumentNullException("data"); 
      if (string.IsNullOrEmpty(filename)) filename = "export.csv"; 

      HttpResponse resp = System.Web.HttpContext.Current.Response; 
      resp.Clear(); 
      // remove this line if you don't want to prompt the user to save the file 
      resp.AddHeader("Content-Disposition", "attachment;filename=" + filename); 
      // if not saving, try: "application/ms-excel" 
      resp.ContentType = "text/csv"; 
      string csv = GetCsv(headers, data); 
      byte[] buffer = resp.ContentEncoding.GetBytes(csv); 
      resp.AddHeader("Content-Length", buffer.Length.ToString()); 
      resp.BinaryWrite(buffer); 
      resp.End(); 
     } 
     static void WriteRow(string[] row, StringBuilder destination) 
     { 
      if (row == null) return; 
      int fields = row.Length; 
      for (int i = 0; i < fields; i++) 
      { 
       string field = row[i]; 
       if (i > 0) 
       { 
        destination.Append(','); 
       } 
       if (string.IsNullOrEmpty(field)) continue; // empty field 

       bool quote = false; 
       if (field.Contains("\"")) 
       { 
        // if contains quotes, then needs quoting and escaping 
        quote = true; 
        field = field.Replace("\"", "\"\""); 
       } 
       else 
       { 
        // commas, line-breaks, and leading-trailing space also require quoting 
        if (field.Contains(",") || field.Contains("\n") || field.Contains("\r") 
         || field.StartsWith(" ") || field.EndsWith(" ")) 
        { 
         quote = true; 
        } 
       } 
       if (quote) 
       { 
        destination.Append('\"'); 
        destination.Append(field); 
        destination.Append('\"'); 
       } 
       else 
       { 
        destination.Append(field); 
       } 

      } 
      destination.AppendLine(); 
     } 
     static string GetCsv(string[] headers, IEnumerable<string[]> data) 
     { 
      StringBuilder sb = new StringBuilder(); 
      if (data == null) throw new ArgumentNullException("data"); 
      WriteRow(headers, sb); 
      foreach (string[] row in data) 
      { 
       WriteRow(row, sb); 

      } 
      return sb.ToString(); 
     } 
2

Vous pouvez le faire de cette façon.

private void ExportButton_Click(object sender, System.EventArgs e) 
{ 
    Response.Clear(); 
    Response.Buffer = true; 
    Response.ContentType = "application/vnd.ms-excel"; 
    Response.Charset = ""; 
    this.EnableViewState = false; 
    System.IO.StringWriter oStringWriter = new System.IO.StringWriter(); 
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter); 
    this.ClearControls(dataGrid); 
    dataGrid.RenderControl(oHtmlTextWriter); 
    Response.Write(oStringWriter.ToString()); 
    Response.End(); 
} 

exemple complet here

+0

Cette méthode ne conserve pas le texte qui peut être dans une langue étrangère, thaïlandais ou japonais – htm11h

0

le fera.

Vous pouvez voir des exemples ASP.NET dynamiques avec le code source C# et VB here. Plusieurs de ces exemples illustrent la conversion d'un DataSet ou DataTable en Excel - et vous pouvez facilement obtenir un DataSet ou un DataTable à partir d'un DataGrid. Vous pouvez télécharger l'essai gratuit here si vous voulez l'essayer vous-même.

Disclaimer: Je possède SpreadsheetGear LLC