Datagrid を Excel にエクスポートする最良の方法は何ですか? データグリッドをエクセルにエクスポートした経験がないので、データグリッドをエクセルにエクスポートする方法を知りたいです。私は多くの方法があることを読みましたが、単純なエクスポートをデータグリッド関数に変換することを考えています.私はasp.net C#を使用しています
乾杯..
Datagrid を Excel にエクスポートする最良の方法は何ですか? データグリッドをエクセルにエクスポートした経験がないので、データグリッドをエクセルにエクスポートする方法を知りたいです。私は多くの方法があることを読みましたが、単純なエクスポートをデータグリッド関数に変換することを考えています.私はasp.net C#を使用しています
乾杯..
最も簡単な方法は、単純に csv または html (特に a <table><tr><td>...</td></tr>...</table>
) を出力に書き込み、content-type ヘッダーを介して 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();
}
次の方法で実行できます。
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();
}
ここに完全な例があります。
SpreadsheetGear for .NETがそれを行います。
C# と VB のソース コードを含む ASP.NET のライブ サンプルは、こちら で見ることができます。これらのサンプルのいくつかは、DataSet または DataTable を Excel に変換する方法を示しており、DataGrid から DataSet または DataTable を簡単に取得できます。自分で試してみたい場合は、こちらから無料試用版をダウンロードできます。
免責事項: 私は SpreadsheetGear LLC を所有しています