Response.ContentType = "application/vnd.ms-excel";What if we need more format such as PDF? You can export data to a few other popular formats by using Crystal's ReportDocument if you have Crystal Reports available:
string separator = "\t";
foreach (DataColumn dc in dataTable.Columns)
{
Response.Write(separator + dc.ColumnName );
}
Response.Write("\n");
foreach (DataRow dr in dataTable.Rows)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
Response.Write(separator + dr[i].ToString());
}
Response.Write("\n");
}
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Shared; using System.IO; private void ExportReport() { MemoryStream oStream = new MemoryStream(); string filename = string.Empty; try { ReportDocument crReport = new ReportDocument(); string reportFile = "CrystalReport1.rpt"; string reportPath = string.Format("{0}/{1}", Server.MapPath("."), reportFile); crReport.Load(reportPath); ReportDataSetTableAdapters.UtilityTableAdapter ad = new ReportDataSetTableAdapters.UtilityTableAdapter(); ReportDataSet.UtilityDataTable ut = ad.GetAllData(); crReport.SetDataSource((DataTable)ut); switch (SelectedType) { case "1": //Rich Text (RTF) oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.RichText); Response.ContentType = "application/rtf"; filename = "data.rtf"; break; case "2": //PDF oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.PortableDocFormat); Response.ContentType = "application/pdf"; filename = "data.pdf"; //in case you want to export it as an attachment use the line below //crReport.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Your Exported File Name"); break; case "3": //MS Word (DOC) oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.WordForWindows); Response.ContentType = "application/doc"; filename = "data.doc"; break; case "4": //MS Excel (XLS) oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.Excel); Response.ContentType = "application/vnd.ms-excel"; filename = "data.xls"; break; default: //PDF oStream = (MemoryStream)crReport.ExportToStream(ExportFormatType.PortableDocFormat); Response.ContentType = "application/pdf"; filename = "data.pdf"; break; } //write report to the Response stream byte[] dataByte = oStream.ToArray(); Response.Charset = ""; Response.AddHeader("content-disposition", "fileattachment;filename=" + filename); Response.ContentType = "application/octet-stream"; Response.BinaryWrite(dataByte); Response.Flush(); Response.Clear(); Response.End(); } catch (Exception ex) { ErrorLog.Write(ex); } finally { //clear stream oStream.Flush(); oStream.Close(); oStream.Dispose(); } }
Just a side note if you can not import Crystal merge module into your VS2003, then you need to register the dll again:
regsvr32 "C:\Program Files\Common Files\Microsoft Shared\MSI Tools\mergemod.dll"