gpt4 book ai didi

c# - 将数据网格导出到 excel asp

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:18 25 4
gpt4 key购买 nike

将 Datagrid 导出到 excel 的最佳方法是什么?我没有任何将数据网格导出到 excel 的经验,所以我想知道你们如何将数据网格导出到 excel。我读到有很多方法,但我想做一个简单的导出 excel 到数据网格函数。我正在使用 asp.net C#

干杯..

最佳答案

最简单的方法是简单地将 csv 或 html(特别是 <table><tr><td>...</td></tr>...</table>)写入输出,并通过内容类型 header 假装它是 excel 格式。 Excel 会很乐意加载其中之一; csv 更简单...

这是一个类似的示例(它实际上采用 IEnumerable,但它与任何来源(例如 DataTable,遍历行)都是相似的。

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

关于c# - 将数据网格导出到 excel asp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/271485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com