|
发表于 2020-6-29 16:30:01
|
显示全部楼层
private void btnMIME_Click(object sender, System.EventArgs e)
{
BindData();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "inline;filename="
+ HttpUtility.UrlEncode("下载文件.xls",Encoding.UTF8 ) );
//如果输出为Word,修改为以下代码
//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"));
}
//从DataSet到出到Excel
#region 从DataSet到出到Excel
/// 导出指定的Excel文件
public void ExportToExcel(DataSet ds,string strExcelFileName)
{
if (ds.Tables.Count==0 || strExcelFileName=="") return;
doExport(ds,strExcelFileName);
}
/// 执行导出
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();//垃圾回收
}
#endregion
} |
|