最近在做将数据导出到excel,网上看了下,有很多种方法,我也试了几种,以前有用java做过导出excel的,java是导入poi包,现在发现.net是添加NPOI的引用,基本方法和java的差不了多少,下面是我做的添加NPOI的引用来导出excel的方法:
EXport.ashx:
<%@ WebHandler Language="C#" Class="EXport" %> using System; using System.Web; using NPOI.HSSF.UserModel; using ETL.BLL; using System.Data; public class aaaaa : IHttpHandler { BLLETL bll = new BLLETL(); public void ProcessRequest(HttpContext context) { string aa = context.Request["str"]; if (aa != null) { context.Response.Write(aa); string filename = DateTime.Now.ToString("yyyyMMdd"); context.Response.ContentType = "application/x-excel"; context.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xls"); //创建workbook HSSFWorkbook workbook = new HSSFWorkbook(); //创建sheet HSSFSheet sheet = workbook.CreateSheet(); DataSet ds = bll.GetAllDataSet(); int colHeaders = 0; //创建标题行 HSSFRow Header = sheet.CreateRow(colHeaders); Header.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); Header.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); Header.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); Header.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); Header.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); Header.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue("日志时间"); int rownum = 1; foreach (DataRow row in ds.Tables[0].Rows) { HSSFRow roww = sheet.CreateRow(rownum); roww.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(row[0].ToString()); roww.CreateCell(1, HSSFCell.CELL_TYPE_NUMERIC).SetCellValue(row[1].ToString()); roww.CreateCell(2, HSSFCell.CELL_TYPE_STRING).SetCellValue(row[2].ToString()); roww.CreateCell(3, HSSFCell.CELL_TYPE_STRING).SetCellValue(row[3].ToString()); roww.CreateCell(4, HSSFCell.CELL_TYPE_STRING).SetCellValue(row[4].ToString()); roww.CreateCell(5, HSSFCell.CELL_TYPE_STRING).SetCellValue(row[5].ToString()); rownum++; } workbook.Write(context.Response.OutputStream); } } public bool IsReusable { get { return false; } } }
Export.html中:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
var str = 1;
window.location.href = "EXport.ashx?str=" + str;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="导出" id="btnExport" />
</div>
</form>
</body>
</html>
<head runat="server">
<title></title>
<script type="text/javascript" src="js/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function () {
var str = 1;
window.location.href = "EXport.ashx?str=" + str;
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="导出" id="btnExport" />
</div>
</form>
</body>
</html>