文件的下载

本文介绍如何将数据库中的数据导出到文本文件及Excel文件的方法。具体步骤包括设置响应类型、添加头部信息以便浏览器识别文件类型及名称,以及使用循环遍历数据库表中的数据并写入文件。

1.将数据库的数据保存到文本文件中:

context.Response.ContentType = "text/plain";
//增加另存为功能
//增加Content-Disposition是告诉浏览器,这个返回的内容是"附件形式",要给用户保存,filename是建议的文件名
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode("动态文件.txt"));
DataTable table = SQLHelper.ExecuteReader("select * from userinfo");
foreach (DataRow row in table.Rows)
{
    context.Response.Write(row["name"].ToString() + "\t" + row["age"].ToString() + "\r\n");
}

2.将数据库的数据保存到EXCEL中

context.Response.ContentType = "application/ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment;filename=" +
    context.Server.UrlEncode("人员列表.xls"));
IWorkbook workbook = new HSSFWorkbook();//new XSSFWorkbook();//xlsx
ISheet sheet = workbook.CreateSheet("人员列表");
DataTable dt = SQLHelper.ExecuteReader("select * from Users");
for (int i = 0; i < dt.Rows.Count; i++)
{
    IRow excelRow = sheet.CreateRow(i);
    DataRow dataRow = dt.Rows[i];
    ICell cell0 = excelRow.CreateCell(0);
    cell0.SetCellValue((string)dataRow["username"]);

    ICell cell1 = excelRow.CreateCell(1);
    cell1.SetCellValue((int)dataRow["age"]);
}
workbook.Write(context.Response.OutputStream);

 

转载于:https://www.cnblogs.com/genesis/p/4663958.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值