To output GridView or DataGrid to Excel file, one can use:
- Use oledb classes to create and write data into Excel file
- If datasource is DataTable or DataSet, use writeXml method
- Use RenderControl method of Control class
Taking the latest way as an example
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.WriteLine("<table cellspacing=\"0\", rules=\"all\", border=\"1\">");
gvResult.RenderControl(htmlWrite);
htmlWrite.WriteLine("</table>");
System.Text.UnicodeEncoding encoding = new System.Text.UnicodeEncoding();
String fileName = Guid.NewGuid().ToString() + ".xls";
String path = @"c:\temp\";
File.WriteAllText(path + fileName, stringWrite.ToString(), encoding);
No comments:
Post a Comment