Datagrid export for Excel asp

What's the best way to export Datagrid to Excel? I have no experience with exporting datagrid to succeed, so I want to know how you guys export datagrid in order to succeed. I read that there are many ways, but i think just do a simple excel export for datagrid function.i use asp.net c #

greetings ..

+1


source to share


4 answers


The easiest way is to just write either csv or html (specifically a <table><tr><td>...</td></tr>...</table>

) for the output, and just pretend it is in excel format via the content type header. Excel will be loaded too; csv is easier ...

Here's a similar example (it actually accepts an IEnumerable, but it will be similar to any source (e.g. DataTable

iterates over strings).



        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();
        }

      

+6


source


You can do it like this:

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();
}

      



Complete an example here .

+2


source


Export values ​​to Excel or Word or PDF Check http://techdotnets.blogspot.com/

0


source


SpreadsheetGear for .NET will do this.

You can see live ASP.NET samples with C # and VB source code here . Some of these examples demonstrate converting a DataSet or DataTable to Excel - and you can easily get a DataSet or DataTable from a DataGrid. You can download a free trial here if you want to try it yourself.

Disclaimer: I own SpreadsheetGear LLC

0


source







All Articles