该链接有导入,导出源码,我的代码有下链接改写,完善而成的,
http://www.cnblogs.com/colder/p/3611906.html
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.IO;
using System.Data;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using NPOI.HSSF.Util;
using NPOI.HSSF.Extractor;
using NPOI.SS.UserModel;
using System.Web.UI.HtmlControls;
private void to_excel()
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1");
MemoryStream ms = new MemoryStream();
ICellStyle HeadercellStyle = workbook.CreateCellStyle();
HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//字体
NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
headerfont.Boldweight = (short)FontBoldWeight.Bold;
HeadercellStyle.SetFont(headerfont);
//用column name 作为列名
string[] temArr = { "帐号", "子帐号", "客户经理号(8位)", "开户日期(YYYYMMDD)" };
List
int icolIndex = 0;
IRow headerRow = sheet.CreateRow(0);
foreach (var item in headlist)
{
ICell cell = headerRow.CreateCell(icolIndex);
cell.SetCellValue(item);
cell.CellStyle = HeadercellStyle;
icolIndex++;
}
ICellStyle cellStyle = workbook.CreateCellStyle();
//为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
cellfont.Boldweight = (short)FontBoldWeight.Normal;
cellStyle.SetFont(cellfont);
//建立内容行
TMSDataContext dc = new TMSDataContext();
var lctlist = dc.wd_lct_dq_import.ToList();
int iRowIndex = 1;
//int iCellIndex = 0;
foreach (var lct in lctlist)
{
IRow DataRow = sheet.CreateRow(iRowIndex);
//第1列 账号
ICell cell = DataRow.CreateCell(0);
cell.SetCellValue(lct.zh);
cell.CellStyle = cellStyle;
//第2列 子账号
cell = DataRow.CreateCell(1);
cell.SetCellValue(lct.zh_sub);
cell.CellStyle = cellStyle;
//第3列 客户经理号
cell = DataRow.CreateCell(2);
cell.SetCellValue(lct.emp_lch);
cell.CellStyle = cellStyle;
//第4列 开户日期
cell = DataRow.CreateCell(3);
cell.SetCellValue(lct.kh_rq);
cell.CellStyle = cellStyle;
iRowIndex++;
}
//自适应列宽度
for (int i = 0; i < icolIndex; i++)
{
sheet.AutoSizeColumn(i);
}
workbook.Write(ms);
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=EmptyWorkbook.xls"));
Response.BinaryWrite(ms.ToArray());
workbook = null;
ms.Close();
ms.Dispose();
}