导出NPOI

 

table:表

dataName:文件名

listNme:列名

public void RenderToExcel(DataTable table, string dataName, string[] listNme)
{
var countL = listNme.Length;
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet(dataName);//创建工作表
sheet.SetColumnWidth(1, 40 * 256);
sheet.SetColumnWidth(2, 30 * 256);
sheet.SetColumnWidth(3, 30 * 256);
sheet.SetColumnWidth(4, 20 * 256);
sheet.SetColumnWidth(5, 20 * 256);

#region 标题
IRow row = sheet.CreateRow(0);//在工作表中添加一行
for (int i = 0; i < listNme.Length; i++)
{
ICell cell = row.CreateCell(i);//在行中添加一列
cell.SetCellValue(listNme[i]);//设置列的内容

}
#endregion

#region 填充数据
for (int i = 1; i <= table.Rows.Count; i++)//遍历DataTable行
{
DataRow dataRow = table.Rows[i - 1];
row = sheet.CreateRow(i);//在工作表中添加一行
var n = table.Columns.Count;
for (int j = 0; j < table.Columns.Count; j++)//遍历DataTable列
{

ICell cell = row.CreateCell(j);//在行中添加一列
if (countL < n)
{
if (j<5)
{
if (j >= 3)
{
cell.SetCellValue(dataRow[j + 1].ToString());//设置列的内容
}
else
{
cell.SetCellValue(dataRow[j].ToString());//设置列的内容
}
}

}
else
{
cell.SetCellValue(dataRow[j].ToString());//设置列的内容

}

}
}
#endregion

#region 输出到Excel
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(dataName + "_" + DateTime.Now.ToString("yyyy-MM-dd"), System.Text.Encoding.UTF8)));
Response.BinaryWrite(ms.ToArray());
Response.End();
//var file = new FileStream("C:\\Users\\Administrator\\Desktop\\" + dataName + ".xls", FileMode.Create);
//workbook.Write(file);
//file.Close();
workbook = null;
ms.Close();
ms.Dispose();
#endregion

}

posted @ 2015-06-24 11:23  成小伟  阅读(181)  评论(0编辑  收藏  举报