.net下 用NPOI 怎么将DataReader数据导出为Excel文件
while (reader.Read())
{
HSSFRow row = sheet.CreateRow(rowIndex);
for (int i = 0; i < reader.FieldCount; i++)
{
HSSFCell cell = row.CreateCell(i);
cell.SetCellValue(Convert.ToString(reader.GetValue(i)));
}
//
// 我想Read()一行就写入到Excel文件一行...
//
}
1 <%@ WebHandler Language="C#" Class="DownExcel1" %>
2
3 using System;
4 using System.Web;
5 using NPOI.HSSF.UserModel;
6 using System.Data.SqlClient;
7 using System.Data;
8
9 public class DownExcel1 : IHttpHandler
10 {
11
12 public void ProcessRequest(HttpContext context)
13 {
14 context.Response.ContentType = "application/x-excel";
15 string filename = HttpUtility.UrlEncode("用户数据.xls");
16 context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
17 HSSFWorkbook hssfworkbook = new HSSFWorkbook();
18 HSSFSheet sheet = (HSSFSheet)hssfworkbook.CreateSheet();
19 HSSFRow row = (HSSFRow)sheet.CreateRow(0);
20 row.CreateCell(0, NPOI.SS.UserModel.CellType.STRING).SetCellValue("用户名");
21 row.CreateCell(1, NPOI.SS.UserModel.CellType.STRING).SetCellValue("喜爱的颜色");
22
23 using (SqlConnection conn = new SqlConnection("Data Source=***;Initial Catalog=database;User ID=sa;Password=***"))
24 {
25 conn.Open();
26 using (IDbCommand cmd = conn.CreateCommand())
27 {
28 cmd.CommandText = "select UserName,FavoriteColor from Users ";
29 using (IDataReader reader=cmd.ExecuteReader())
30 {
31 int rownum = 1;
32 while (reader.Read())
33 {
34 string username = reader.GetString(reader.GetOrdinal("UserName"));
35 string fc = reader.GetString(reader.GetOrdinal("FavoriteColor"));
36 row = (HSSFRow)sheet.CreateRow(rownum);
37 row.CreateCell(0, NPOI.SS.UserModel.CellType.STRING).SetCellValue(username);
38 row.CreateCell(1, NPOI.SS.UserModel.CellType.STRING).SetCellValue(fc);
39 rownum++;
40 }
41 }
42 }
43 }
44 hssfworkbook.Write(context.Response.OutputStream);
45
46 }
47
48 public bool IsReusable
49 {
50 get
51 {
52 return false;
53 }
54 }
55
56 }