using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.IO;
using System.Reflection; namespace WebApplication1.Controllers
{
public class Info
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TestController : Controller
{
// GET: Test
public ActionResult Index()
{
List<Info> list = new List<Info>(); for (int i = ; i < ; i++)
{
Info info = new Info();
info.Id = i + ;
info.Name = "张三" + (i + );
list.Add(info);
}
Dictionary<string, string> columnInfo = new Dictionary<string, string>();
columnInfo.Add("Id","序号");
columnInfo.Add("Name", "姓名");
byte[] btyBytes=null;
var a = ExportExcelTest<Info>(list, @"F://111.xlsx", ref btyBytes, columnInfo, ); return View();
} #region NPOI大数据量多个sheet导出 /// <summary>
/// 大数据量多个sheet导出
/// </summary>
/// <typeparam name="T">数据源实体类</typeparam>
/// <param name="objList">数据源</param>
/// <param name="fileName">文件名称</param>
/// <param name="btyBytes">导出数据流</param>
/// <param name="columnInfo">显示列对应数据字典</param>
/// <param name="listCount">每个sheet包含数据条数</param>
/// <returns></returns>
public static bool ExportExcelTest<T>(List<T> objList, string fileName, ref byte[] btyBytes,
Dictionary<string, string> columnInfo = null, int listCount = )
{
bool bResult = false;
//在内存中生成一个Excel文件:
XSSFWorkbook book = new XSSFWorkbook();
if (objList != null && objList.Count > )
{
double sheetCount = Math.Ceiling((double)objList.Count / listCount);
for (int i = ; i < sheetCount; i++)
{
ISheet sheet = null;
sheet = book.CreateSheet("sheet" + i);
sheet.DefaultRowHeight = * ;
List<T> list = new List<T>();
list = objList.Skip<T>(listCount * i).Take<T>(listCount).ToList(); int rowIndex = ;
int StartColIndex = ;
int colIndex = StartColIndex; //创建表头样式
ICellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.CENTER;
style.WrapText = true;
IFont font = book.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = (short)NPOI.SS.UserModel.FontBoldWeight.BOLD;
font.FontName = "简体中文";
style.SetFont(font);//HEAD 样式 Type myType = null;
myType = objList[].GetType();
//根据反射从传递进来的属性名信息得到要显示的属性
List<PropertyInfo> myPro = new List<PropertyInfo>();
PropertyInfo[] properties = myType.GetProperties(); #region 定义表头
int m = ;
if (columnInfo != null)
{
var rowheader = sheet.CreateRow();
rowheader.Height = rowheader.Height = * ;
foreach (string cName in columnInfo.Keys)
{
PropertyInfo p = myType.GetProperty(cName);
if (p != null)
{
myPro.Add(p);
rowheader.CreateCell(m).SetCellValue(columnInfo[cName]);
m++;
}
}
}
#endregion
#region 定义表体并赋值
//如果没有找到可用的属性则结束
if (myPro.Count == ) { return bResult; }
foreach (T obj in list)
{
int n = ;
if (sheet != null)
{
rowIndex++;
var sheetrow = sheet.CreateRow(rowIndex);
sheetrow.Height = sheetrow.Height = * ;
foreach (PropertyInfo p in myPro)
{
dynamic val = p.GetValue(obj, null) ?? "";
string valtype = val.GetType().ToString();
if (valtype.ToLower().IndexOf("decimal", StringComparison.Ordinal) > -)
{
val = Convert.ToDouble(val);
}
else if (valtype.ToLower().IndexOf("datetime", StringComparison.Ordinal) > -)
{
val = val.ToString("yyyy-MM-dd HH:mm:ss");
if (val.Equals("0001-01-01 00:00:00"))
{
val = "";
}
}
sheetrow.CreateCell(n).SetCellValue(val);
n++;
}
} }
#endregion
}
}
else
{
//在工作薄中建立工作表
XSSFSheet sheet = book.CreateSheet() as XSSFSheet;
sheet.SetColumnWidth(, * );
if (sheet != null) sheet.CreateRow().CreateCell().SetCellValue("暂无数据!");
} var fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
book.Write(fs);
//try
//{
// HttpResponse rs = System.Web.HttpContext.Current.Response;
// rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
// rs.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
// rs.ContentType = "application/vnd.ms-excel";
// //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet // using (MemoryStream ms = new MemoryStream())
// {
// book.Write(ms);
// btyBytes = ms.GetBuffer();
// rs.AddHeader("Content-Length", btyBytes.Length.ToString());
// rs.BinaryWrite(ms.GetBuffer());
// ms.Flush();
// }
//}
//catch (SystemException ex)
//{
// throw ex;
//}
//catch (ApplicationException ex)
//{
// throw ex;
//}
return bResult;
} #endregion
}
}

最新文章

  1. iPhone CSS media query(媒体查询)
  2. PHP空数组转化为json对象的问题
  3. 图解——VS发布网站详细步骤
  4. 学习笔记TimePicker
  5. 算法_栈的Java的通用数组实现
  6. 我的开发框架(WinForm)3
  7. centos系统安装中文字体几种方法
  8. C++中的#pragma 预处理指令详解
  9. win安装Theano
  10. Hangfire 使用笔记
  11. j2e应用概述
  12. hdu1568 Fibonacci---前4位
  13. Android项目刮刮奖详解(一)
  14. vue.js学习第一天,了解vue.js
  15. odoo开发笔记 -- self详解
  16. Android--UI之ImageSwitcher
  17. 修改tp5的默认配置文件的位置
  18. 百度外卖接口调试 C#版
  19. 常见jsp跳转总结
  20. postgresql----ANY/SOME&amp;&amp;ALL

热门文章

  1. H3C 常用的IPv6地址类型及格式
  2. P1041 查找元素
  3. 洛谷——P1540机器翻译(队列操作)
  4. wireshark使用心得 centos7安装wireshark: yum install wireshark wireshark-gnome
  5. sql临时表与变量表
  6. hibernate_检索策略
  7. javaweb项目启动时自动启动rmi服务器实例
  8. java引用类型的浅拷贝与深拷贝理解
  9. mongodb安装及安装MongoDB报错Verify that you have sufficient privileges to start system services解决方法
  10. 关于SAM和广义SAM