将 Datagrid 导出到 excel asp [英] export Datagrid to excel asp
问题描述
将 Datagrid 导出到 Excel 的最佳方法是什么?我没有将数据网格导出到 excel 的任何经验,所以我想知道你们如何将数据网格导出到 excel.我读到有很多方法,但我想只将一个简单的导出 excel 导出到数据网格函数.我正在使用 asp.net C#
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel. i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#
干杯..
推荐答案
最简单的方法是简单地编写 csv 或 html(特别是 The simplest way is to simply write either csv, or html (in particular, a 这是一个类似的例子(它实际上需要一个 IEnumerable,但它从任何来源(例如 Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a 这篇关于将 Datagrid 导出到 excel asp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!...</td></tr>...</table>) 到输出,并通过内容类型标题简单地假装它是 excel 格式.Excel 将很乐意加载;csv 更简单...
<table><tr><td>...</td></tr>...</table>
) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...DataTable
,循环遍历行)都将是相似的.DataTable
, looping over the rows). 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("
") || field.Contains("
")
|| 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();
}
登录
关闭