我的页面上有一个按钮,允许用户将GridView
的内容保存到Excel。进行工作的类是从View
派生的,而不是Page
,这里是到目前为止的代码:
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);
这将导致创建文件,用户可以下载该文件,但是在Excel中打开该文件时,将显示gridview包含表单的全部内容(包括任何JS):
因为这是在View
而非Page
中完成的,所以我无法使用:
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub
...以及使用时:
gridView.RenderControl(...);
单击按钮时出现404错误。
我如何仅以gridview为目标并以适当的格式将其添加到Response
中?
答案 0 :(得分: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) { }
}