复制代码 代码如下:
/// <summary>
/// 导出Excel
/// </summary>
/// <param></param>
/// <param></param>
//方法一:
public void ImportExcel(Page page, DataTable dt)
{
try
{
string filename = Guid.NewGuid().ToString() + ".xls";
string webFilePath = page.Server.MapPath("https://www.jb51.net/" + filename);
CreateExcelFile(webFilePath, dt);
using (FileStream fs = new FileStream(webFilePath, FileMode.OpenOrCreate))
{
//让用户输入下载的本地地址
page.Response.Clear();
page.Response.Buffer = true;
page.Response.Charset = "GB2312";
//page.Response.AppendHeader("Content-Disposition", "attachment;filename=MonitorResult.xls");
page.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
page.Response.ContentType = "application/ms-excel";
// 读取excel数据到内存
byte[] buffer = new byte[fs.Length - 1];
fs.Read(buffer, 0, (int)fs.Length - 1);
// 写到aspx页面
page.Response.BinaryWrite(buffer);
page.Response.Flush();
//this.ApplicationInstance.CompleteRequest(); //停止页的执行
fs.Close();
fs.Dispose();
//删除临时文件
File.Delete(webFilePath);
}
}
catch (Exception ex)
{
throw ex;
}
}
方法二:
复制代码 代码如下: