0

I have a button on my page that allows a user to save the contents of a GridView to Excel. The class that does the work is derived from a View and not a Page here is the code so far:

Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=file.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";

StringBuilder sb = newStringBuilder();
StringWriter sw = newStringWriter(sb);
Html32TextWriter htw = newHtml32TextWriter(sw);
Page page = new Page();
HtmlForm f = newHtmlForm();

page.Controls.Add(f);
f.Controls.Add(gridView);
HttpContext.Current.Server.Execute(page, htw, true);

Response.Write(sb);

This results in a file being created and the user can download it but when opened in Excel the entire contents of the gridview's containing form is shown (including any JS):

enter image description here

Because this done in a View and not a Page I cannot use:

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)

End Sub

...and when using:

gridView.RenderControl(...);

I get a 404 error when clicking on the button.

How do I target just the gridview and allow that to be added to the Response in a suitable format?

Agamemnon
  • 587
  • 2
  • 15
  • 44
  • This code doesn't create Excel files at all. It creates an HTML file with a fake extension and content type. Use a library like EPPlus to create real `xlsx` files. `xls` is an obsolete format abandoned 12 years ago. – Panagiotis Kanavos Nov 06 '18 at 13:20
  • .xls was purely to allow legacy devices etc to access the file. My attempt above was a result of various limitations that appear to exclude common responses to similar questions. – Agamemnon Nov 06 '18 at 13:31

1 Answers1

0
  private void ExtractDataToCSV(DataGridView dgv)
    {
        try
        {
            // Don't save if no data is returned
            if (dgv.Rows.Count == 0)
            {
                return;
            }
            StringBuilder sb = new StringBuilder();
            // Column headers
            string columnsHeader = "";
            for (int i = 0; i < dgv.Columns.Count; i++)
            {
                columnsHeader += dgv.Columns[i].Name + ",";
            }
            sb.Append(columnsHeader + Environment.NewLine);
            // Go through each cell in the datagridview
            foreach (DataGridViewRow dgvRow in dgv.Rows)
            {
                // Make sure it's not an empty row.
                if (!dgvRow.IsNewRow)
                {
                    for (int c = 0; c < dgvRow.Cells.Count; c++)
                    {
                        // Append the cells data followed by a comma to delimit.

                        sb.Append(dgvRow.Cells[c].Value + ",");
                    }
                    // Add a new line in the text file.
                    sb.Append(Environment.NewLine);
                }
            }
            // Load up the save file dialog with the default option as saving asva.csvfile.
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV files (*.csv)|*.csv";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                // If they've selected a save location...
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
                {
                    // Write the stringbuilder text to the the file.
                    sw.WriteLine(sb.ToString());
                }
            }
            // Confirm to the user it has been completed.
            MessageBox.Show("CSV file saved.");

        }
        catch (Exception ex) { }
    }
Mazen Ahmed
  • 100
  • 5