public static void Export<T>(IList<T> sourceData, IList<String> headerList = null, string fileName = null)
{
if (sourceData == null)
throw new ArgumentNullException("sourceData");
IWorkbook workbook = new HSSFWorkbook();
var count = 0;
var sheet = workbook.CreateSheet("Sheet1");
var properties = TypeDescriptor.GetProperties(typeof(T));
var row = sheet.CreateRow(0);
//如果没有自定义的行首,那么采用反射集合的属性名做行首
var headerCount = headerList != null ? headerList.Count : properties.Count;
for (var i = 0; i < headerCount; i++) //生成sheet第一行列名
{
var cell = row.CreateCell(count++);
if (headerList == null)
{
cell.SetCellValue(String.IsNullOrEmpty(properties[i].Description)
? properties[i].Name
: properties[i].Description);
}
else
cell.SetCellValue(headerList[i]);
}
//将数据导入到excel表中
for (var i = 0; i < sourceData.Count; i++)
{
row = sheet.CreateRow(i + 1);
count = 0;
for (var j = 0; j < properties.Count; j++)
{
var cell = row.CreateCell(count++);
var value = properties[j].GetValue(sourceData[i]);
//日期格式导出修改 huangwei 2013-12-23 yyyy-MM-dd HH:ss
//格式应该是"yyyy-MM-dd HH:mm"
cell.SetCellValue(value == null ? String.Empty
: (value is DateTime ? ((DateTime)value).ToString("yyyy-MM-dd HH:mm") : value.ToString()));
}
}
//定义文件名
if (string.IsNullOrEmpty(fileName))
fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
else
fileName = fileName + ".xls";
//当前http头信息
var response = HttpContext.Current.Response;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
response.Clear();
//Write the stream data of workbook to the root directory
var file = new MemoryStream();
workbook.Write(file);
file.WriteTo(response.OutputStream);
response.End();
}
导出数据到Excel 2003 单个Sheet页(NPOI)
最新推荐文章于 2019-07-27 10:19:14 发布