首页 新闻 会员 周边

NPOI导出

0
悬赏园豆:50 [待解决问题]

.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文件一行...
//
}

问题补充: 我是想Read()一行,就写入到Excel一行 、 这样应该能减少内存的占用 , 而不是Read()完了在一次写入
Kar)的主页 Kar) | 初学一级 | 园豆:134
提问于:2011-04-14 14:47
< >
分享
所有回答(1)
0
用一般程序可以解决,提供给你参考:
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 }
加百力 | 园豆:533 (小虾三级) | 2011-04-14 14:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册