using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.ContentType = "application/x-excel";
string fileName = HttpUtility.UrlEncode("数据库文备份.xls");
Response.AddHeader("Content-Disposition", "attachment; fileName=" + fileName); //添加http协议报文;
HSSFWorkbook workbook = new HSSFWorkbook(); //创建一个xls;
ISheet sheet = workbook.CreateSheet(); //创建一个Sheet页
string connectString = @"server=localhost;database=NpoiTest; uid=sa; pwd=sa";
SqlConnection connection = new SqlConnection(connectString);
connection.Open();
using (IDbCommand cmd = connection.CreateCommand()) //接口编徎;
{
cmd.CommandText = "select * from Users";
using (IDataReader reader = cmd.ExecuteReader())
{
int rowsNum = 0; //行号
while (reader.Read())
{
//根据字段名找出ID
string LoginId = reader.GetString(reader.GetOrdinal("LoginId"));
string LoginPwd = reader.GetString(reader.GetOrdinal("LoginPwd"));
string Name = reader.GetString(reader.GetOrdinal("Name"));
string QQ = reader.GetString(reader.GetOrdinal("QQ"));
string Mail = reader.GetString(reader.GetOrdinal("Mail"));
/******************以上代码对应数据库表中的字段*********************/
IRow row = sheet.CreateRow(rowsNum);
row.CreateCell(0).SetCellValue(LoginId);
row.CreateCell(1).SetCellValue(LoginPwd);
row.CreateCell(2).SetCellValue(Name);
row.CreateCell(3).SetCellValue(QQ);
row.CreateCell(4).SetCellValue(Mail);
/******************以上代码对应Excel文件的列************************/
rowsNum++;
}
}
}
workbook.Write(Response.OutputStream); //输出到流中
}
}
}
需要的DLL文件包我已经上传在资源里了 自行下载.