利用npoi导出数据库内容到excel表格

创建一个html页面,仅有一个链接即可<a href="users.ashx">下载用户列表</a>

users.ashx.cs的主要代码如下:

<textarea cols="50" rows="15" name="code" class="c-sharp">context.Response.ContentType = "application/x-excel"; string filename = HttpUtility.UrlEncode("用户信息表.xls");//增加报文头使其为附件形式 context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename); HSSFWorkbook workbook = new HSSFWorkbook();//创建一个xls文件 HSSFSheet sheet = workbook.CreateSheet("用户表");//创建一个名为&ldquo;用户表&rdquo;的sheet HSSFRow row_title = sheet.CreateRow(0);//添加表头 row_title.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("用户名"); row_title.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("密码"); using (SqlConnection conn = new SqlConnection(@"Data Source=./SQLEXPRESS;AttachDbFilename=|DataDirectory|/Users.mdf;Integrated Security=True;User Instance=True")) { conn.Open(); using (IDbCommand cmd = conn.CreateCommand()) { cmd.CommandText="select * from T_user"; using (IDataReader reader = cmd.ExecuteReader()) { int i = 1; while (reader.Read()) { string userName = reader.GetString(reader.GetOrdinal("userName")); string passWord = reader.GetString(reader.GetOrdinal("PassWord")); HSSFRow row = sheet.CreateRow(i);//创建行,以下两行是创建单元格并赋值 row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(userName); row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(passWord); i++; } workbook.Write(context.Response.OutputStream);//输出流 } } }</textarea>

你可能感兴趣的:(html,数据库,String,cmd,Excel,Security)