|
private void btnMIME_Click(object sender, System.EventArgs e)
{
BindData();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename="
+ HttpUtility.UrlEncode("Download file.xls",Encoding.UTF8) );
The
//If the output is Word, modify to the following code
//Response.ContentType = "application/ms-word"
//Response.AddHeader("Content-Disposition", "inline;filename=test.doc")
StringBuilder sb=new StringBuilder();
System.IO.StringWriter sw = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
sb.Append("<html><body>");
dgShow.RenderControl(hw);
sb.Append("</body></html>");
Response.Write(sb.ToString());
Response.End();
}
private void btnCom_Click(object sender, System.EventArgs e)
{
ExportToExcel(BindData(),Server.MapPath("ComExcel.xls"));
The
}
//From DataSet to Excel
#region From DataSet to Out to Excel
/// Export the specified Excel file
public void ExportToExcel(DataSet ds,string strExcelFileName)
{
if (ds.Tables.Count==0 || strExcelFileName=="") return;
doExport(ds,strExcelFileName);
}
/// Perform export
private void doExport(DataSet ds,string strExcelFileName)
{
Excel.Application excel = new Excel.Application();
int rowIndex=1;
int colIndex=0;
excel.Application.Workbooks.Add(true);
System.Data.DataTable table=ds.Tables[0];
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1,colIndex]=col.ColumnName;
}
foreach(DataRow row in table.Rows)
{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
}
}
excel.Visible=false;
excel.ActiveWorkbook.SaveAs(strExcelFileName+".XLS",Excel.XlFileFormat.xlExcel9795,null,null,false,false,Excel.XlSaveAsAccessMode.xlNoChange,null,null,null,null,null);
excel.Quit();
excel=null;
GC.Collect();//Garbage collection
}
#endregion
} |
|