How to DataTable export to Excel in asp.net

C#

static public void ExportDataTable(DataTable dt, string filename)
{
   string attachment = "attachment; filename=" + filename + "";
   HttpContext.Current.Response.Clear();
   HttpContext.Current.Response.AddHeader("content-disposition", attachment);
   HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; //office 2003
   string sTab = "";
   foreach (DataColumn dc in dt.Columns)
   {
      HttpContext.Current.Response.Write(sTab + dc.ColumnName);
      sTab = "\t";
   }
   HttpContext.Current.Response.Write("\n");
   int i;
   foreach (DataRow dr in dt.Rows)
   {
      sTab = "";
      for (i = 0; i < dt.Columns.Count; i++)
      {
         HttpContext.Current.Response.Write(sTab + dr[i].ToString());
         sTab = "\t";
      }
      HttpContext.Current.Response.Write("\n");
   }
   HttpContext.Current.Response.End();
}

Vb.net

Public Shared Sub ExportDataTable(dt As DataTable, filename As String)
	Dim attachment As String = "attachment; filename=" & filename & ""
	HttpContext.Current.Response.Clear()
	HttpContext.Current.Response.AddHeader("content-disposition", attachment)
	HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"
	'office 2003
	Dim sTab As String = ""
	For Each dc As DataColumn In dt.Columns
		HttpContext.Current.Response.Write(sTab + dc.ColumnName)
		sTab = vbTab
	Next
	HttpContext.Current.Response.Write(vbLf)
	Dim i As Integer
	For Each dr As DataRow In dt.Rows
		sTab = ""
		For i = 0 To dt.Columns.Count - 1
			HttpContext.Current.Response.Write(sTab & dr(i).ToString())
			sTab = vbTab
		Next
		HttpContext.Current.Response.Write(vbLf)
	Next
	HttpContext.Current.Response.[End]()
End Sub

Đoạn code sau dùng cho Encode : Unicode

   Response.Clear();
   Response.ClearContent();
   Response.ClearHeaders();
   Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
   Response.ContentEncoding = System.Text.Encoding.Unicode;
   Response.ContentType = "application/ms-excel";
   Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
This entry was posted in 4-Coding and tagged , , , , , , , , , , , , , , , , , , , , . Bookmark the permalink.