后台代码:
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
namespace WebUtility
{
/// 将Table的数据导出Excel;
/// 标题为Table的标题;
/// 使用文件操作来完成此功能:
/// 缺点:不能操作Excel;标题可能是英文,没有边框,没有格式;
public class OutExcel:DBUtility.DBHelper
{
/// 导出EXCEL
public int Export(DataTable dt,string FileName)
{
try
{
//文件名;创建;可写
FileStream fs=
new FileStream (FileName,FileMode.Create,FileAccess.Write);
StreamWriter sw=
new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
//标题
string Title = "";
//内容
string Line = "";
for (int i=0;i<dt.Columns.Count;i++)
{
Title = Title + dt.Columns[i].ToString() + " ";
}
//去掉最后的回车符
Title = Title.Substring(0,Title.Length -1);
//将标题写入流
sw.WriteLine(Title);
foreach(DataRow dr in dt.Rows)
{
for (int i=0;i<dt.Columns.Count;i++)
{
Line = Line+dr[i] + " ";
}
Line = Line.Substring(0,Line.Length -1);
//将数据写入文件流
sw.WriteLine(Line);
Line = "";
}
sw.Close();
return 0;
}
catch
{
return 1;
}
}
}
}
前台代码:
protected void btnOut_Click(object sender, EventArgs e)
{
public WebUtility.OutExcel myOut = new WebUtility.OutExcel();
//导出日志到Excel
System.Data.DataTable dt = user.DataSetLoginLog(WebUtility.SysUser.LoginLogType.all).Tables[0];
string DownloadPath = Server.MapPath(".") + "//" + string.Format("登录日志备份{0}.XLS",System.DateTime.Now.ToShortDateString());
//导出
this.myOut.Export(dt, DownloadPath);
//以下代码将 pdf 文件写入客户端浏览器。
Response.ClearContent();
Response.ClearHeaders();
//作为附件下载
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(DownloadPath));
Response.ContentType = "application/ms-excel";
Response.WriteFile(DownloadPath);
Response.Flush();
Response.Close();
//从磁盘删除导出的文件
System.IO.File.Delete(DownloadPath);
}
阅读(824) | 评论(0) | 转发(0) |