ใช้ตัวอย่าง code นี้ในการ export DataTalbe ไปเป็น Excel
public static void ExportToSpreadsheet(DataTable table, string name){HttpContext context = HttpContext.Current;context.Response.Clear();foreach (DataColumn column in table.Columns){context.Response.Write(column.ColumnName + ";");}context.Response.Write(Environment.NewLine);foreach (DataRow row in table.Rows){for (int i = 0; i < table.Columns.Count; i++){context.Response.Write(row[i].ToString().Replace(";", string.Empty) + ";");}context.Response.Write(Environment.NewLine);}context.Response.ContentType = "text/csv";context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");context.Response.End();}การเรียกใช้ด้วย
ExportToSpreadsheet(table, "products");
สามารถนำไปประยุกต์เป็น HTTP Handler เพื่อเรียกใช้ได้
Page rendered at Sunday, February 05, 2012 1:53:11 PM (SE Asia Standard Time, UTC+07:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.