1):添加Excel.dll到引用文件中,並在頁面後臺引用這個命名空間:Using Excel; javascript
2)按鈕事件代碼: java
string filename = "filename"+ ".xls"; //導出Excel的名字
try
{
Excel.Application excel = new Excel.Application();//申明一個對象;
_Workbook book;
_Worksheet sheet;
book = excel.Workbooks.Add(true);
sheet = (Worksheet)book.ActiveSheet;
excel.Cells[1, 1] = "try again";//在單元格中賦值,row&column都是從1開始
excel.Cells[1, 2] = "this is my another report";
excel.Visible = false;
book.SaveCopyAs(Server.MapPath("file")+"\\"+filename);//保存excel在名爲file的文件夾下,這個文件夾必須先存在;
//excel.Quit();//若是不註釋掉,會彈出提示框詢問你是否保存sheet1;
}
catch (Exception ex)
{
Response.Write("script language=javascript>alert('Encounter one error!');history.go(-1)</script>"); //Exception handling
}
//將保存在file文件夾下的excel,以文件流的方式導出
string path = Server.MapPath("file") + "\\" + filename;
System.IO.FileInfo file = new System.IO.FileInfo(path);
Response.Clear(); //[將文件從「服務端」導出到「客戶端」]
Response.Charset = "GB2313"; //[設置寫入流的字符編碼方式爲GB2312]
Response.ContentEncoding = System.Text.Encoding.UTF8; //[設置寫入流的文字編碼格式:UTF8]
//Response.AddHeader("Content-Disposition", "attachment:filename=" + Server.UrlEncode(file.Name));
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));//注意attachment後面是分號不是冒號,否則打開後的excel爲.aspx頁面的HTML代碼;// 添加頭信息,爲"文件下載/另存爲"對話框指定默認文件名
Response.AddHeader("Content-Length", file.Length.ToString());// 添加頭信息,指定文件大小,讓瀏覽器可以顯示下載進度
Response.ContentType = "application/ms-excel";//指定內容類型,導出格式爲excel,也能夠是ms-word,etc;// 指定返回的是一個不能被客戶端讀取的流,必須被下載
Response.WriteFile(file.FullName);// 把文件流發送到客戶端
Response.End(); // 中止頁面的執行
File.Delete(this.FileName);//[關閉文件流] 瀏覽器
} app