您的位置:首页 > 其它

NPOI导入导出Excel (2)

2015-07-18 15:50 399 查看
简单演示一下创建一个Workbook对象,添加一个工作表,在工作表中添加一行一列:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
MemoryStream ms = RenderToExcel(GetTable());
string fileName = @"c:\2.xls";
SaveToFile(ms, fileName);
Response.Write("成功");
}
public MemoryStream RenderToExcel(DataTable table)
{
MemoryStream ms = new MemoryStream();

using (table)
{
IWorkbook workbook = new HSSFWorkbook();

ISheet sheet = workbook.CreateSheet();

IRow headerRow = sheet.CreateRow(0);

// handling header.
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value

// handling value.
int rowIndex = 1;

foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);

foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}

rowIndex++;
}

workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}

return ms;
}
private void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();

fs.Write(data, 0, data.Length);
fs.Flush();

data = null;
}
}
private DataTable GetTable()
{
SqlHelperXhf xhf = new SqlHelperXhf();
string sql = "select calling_no '电话号码',starttime '时间' ,hname '楼盘名称' from [fc_freetel] a where hname<>'无'and a.id = (select min(id) from fc_freetel where calling_no=a.calling_no) order by hname,starttime desc";

return xhf.ExecuteDataTable(sql);

}
private DataTable GetTable(int hid)
{
SqlHelperXhf xhf = new SqlHelperXhf();
string sql = "select calling_no '电话号码',starttime '时间' ,hname '楼盘名称' from [fc_freetel] a where hid=@hid and a.id = (select min(id) from fc_freetel where calling_no=a.calling_no) order by hname,starttime desc";
SqlParameter paramer = new SqlParameter("@hid", hid);
return xhf.ExecuteDataTable(sql,paramer);

}
private DataTable GetTable(int hid1,int hid2,int hid3)
{
SqlHelperXhf xhf = new SqlHelperXhf();
string sql = "select calling_no '电话号码',starttime '时间' ,hname '楼盘名称' from [fc_freetel] a where hid=@hid1 or hid=@hid2 or hid=@hid3 and a.id = (select min(id) from fc_freetel where calling_no=a.calling_no) order by hname,starttime desc";
SqlParameter [] paramers =
{
new SqlParameter("@hid1", hid1),
new SqlParameter("@hid2", hid2),
new SqlParameter("@hid3", hid3)
};
return xhf.ExecuteDataTable(sql, paramers);

}
}

简单演示一下创建一个Workbook对象,添加一个工作表,在工作表中添加一行一列:

using
NPOI.HSSF.UserModel;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: