您的位置:首页 > 数据库

NPOI从数据库中导出Excel

2010-11-21 21:18 197 查看
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using NPOI.DDF;
using System.Data;
using System.Data.SqlClient;
using 导出Excel.DataSet导出ExcelTableAdapters;
namespace 导出Excel
{
/// <summary>
/// Handler1 的摘要说明
/// </summary>
public class Handler1 : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
string dataDir = AppDomain.CurrentDomain.BaseDirectory;
if (dataDir.EndsWith(@"/bin/Debug/")
|| dataDir.EndsWith(@"/bin/Release/"))
{
dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
}
int i=0;
context.Response.ContentType = "application/x-excel";
string filename = HttpUtility.UrlEncode("1.xls");
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
HSSFWorkbook book = new HSSFWorkbook();
HSSFSheet sheet = book.CreateSheet();
T_userTableAdapter adapter = new T_userTableAdapter();
导出Excel.DataSet导出Excel.T_userDataTable table = adapter.GetData();
HSSFRow row2 = sheet.CreateRow(i++);
row2.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("编号");
row2.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("姓名");
adapter.Connection.Open();
foreach (导出Excel.DataSet导出Excel.T_userRow row1 in table)
{
HSSFRow row = sheet.CreateRow(i++);
row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(row1.Id);
row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(row1.Name);

}
adapter.Connection.Close();
book.Write(context.Response.OutputStream);
}

public bool IsReusable
{
get
{
return false;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: