注:点导出的时候回默认是迅雷下,迅雷下的话会把整个界面下下来,不用迅雷下就对了,
界面:
<telerik:RadScriptManager ID="RadScriptManager1" runat="server"></telerik:RadScriptManager>
<telerik:RadButton ID="filtBtn" runat="server" Text="导出" οnclick="filtBtn_Click"></telerik:RadButton>
CS代码:
public class din
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public List<din> getdin()
{
List<din> dlist = new List<din>();
din d1 = new din();
d1.age = 12;
d1.name = "wwww";
d1.sex = "女";
dlist.Add(d1);
din d2 = new din();
d2.age = 124;
d2.name = "rrrr";
d2.sex = "女";
dlist.Add(d2);
return dlist;
}
/// <summary>
/// 导出
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void filtBtn_Click(object sender, EventArgs e)
{
List<din> din = getdin();
LoadFile(din, "工资导出大平台数据");
}
/// <summary>
/// 导出
/// </summary>
/// <param name="sb"></param>
protected void LoadFile(List<din> model, string sTimes)
{
#region 定义excel对象
GC.Collect();
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
_Workbook xBk;
_Worksheet xSt;
string strFileName = "";
System.IO.FileInfo file;
xBk = excel.Workbooks.Add(true);
xSt = (_Worksheet)xBk.ActiveSheet;
#endregion
#region 给execl 赋值
if (model != null) //导出单位
{
string titleInfo = "姓名,年龄,性别";
string[] titles = titleInfo.Split(new char[] { ',' });
for (int i = 0; i < titles.Length; i++)
excel.Cells[1, i + 1] = titles[i];
for (int i = 0; i < model.Count; i++)
{
Type type = model[i].GetType();
for (int j = 0; j < titles.Length; j++)
excel.Cells[i + 2, j + 1] = type.GetProperties()[j].GetValue(model[i], null);
}
}
#endregion
#region 保存文件
xSt.Protect("ABCDEFGHIJKLMNOPQRST", Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, true, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, true, Type.Missing, Type.Missing);
strFileName = Server.MapPath("~/" + sTimes + ".xls");
xBk.SaveCopyAs(strFileName);
xBk.Close(false, null, null);
excel.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
xBk = null;
excel = null;
xSt = null;
GC.Collect();
file = new System.IO.FileInfo(strFileName);
Response.Clear();
//Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加头信息,为"文件下载/另存为"对话框指定默认文件名
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
// 添加头信息,指定文件大小,让浏览器能够显示下载进度
Response.AddHeader("Content-Length", file.Length.ToString());
// 指定返回的是一个不能被客户端读取的流,必须被下载
Response.ContentType = "application/ms-excel";
// 把文件流发送到客户端
Response.WriteFile(file.FullName);
Response.Flush();
file.Delete();
// 停止页面的执行
Response.End();
#endregion
}
}