public static Byte[] RenderDataToExcel<T>(List<T> SourceList, List<String> filter) where T : new()
{
XSSFWorkbook workbook = null;
MemoryStream ms = null;
ISheet sheet = null;
XSSFRow headerRow = null;
try
{
workbook = new XSSFWorkbook();
ms = new MemoryStream();
sheet = workbook.CreateSheet();
headerRow = (XSSFRow)sheet.CreateRow(); PropertyInfo[] arrProperty = RemoveFilterColumn<T>(filter); PropertyInfo pi = null;
for (int i = ; i < arrProperty.Length; i++)
{
pi = arrProperty[i];
headerRow.CreateCell(i).SetCellValue(GetPropertyDescription(pi));
} int rowIndex = ;
for (int i = ; i < SourceList.Count; i++)
{
XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
for (int j = ; j < arrProperty.Length; j++)
{
pi = arrProperty[j];
object piValue = pi.GetValue(SourceList[i], null);
if (piValue == null)
{
dataRow.CreateCell(j).SetCellValue("");
continue;
}
Type pitype = pi.PropertyType;
if (pitype.Name.ToLower().Contains("nullable"))
{
pitype = Nullable.GetUnderlyingType(pitype);
}
//var rowNumberAttr = pi.GetCustomAttributes(typeof(Attribute), false);
//if (rowNumberAttr != null && rowNumberAttr.Length > 0)
//{
// dataRow.CreateCell(j).SetCellValue((i + 1).ToString());
// continue;
//}
if (pitype == typeof(bool))
{
dataRow.CreateCell(j).SetCellValue(Convert.ToBoolean(piValue) ? "是" : "否");
continue;
}
if (pitype.IsEnum)
{
dataRow.CreateCell(j).SetCellValue(EnumHelper.GetDescription(pitype, Convert.ToInt32(piValue)));
continue;
}
if (pitype == typeof(DateTime)
|| pitype == typeof(DateTime?))
{
//var showDateTimeAttr = pi.GetCustomAttributes(typeof(DateTimeFormatAttribute), false);
//if (showDateTimeAttr != null && showDateTimeAttr.Length > 0)
//{
// DateTime nowtime = DateTime.Parse(piValue.ToString());
// arrData[i + 1, j] = nowtime.ToString((showDateTimeAttr[0] as DateTimeFormatAttribute).DataFormatString);
// continue;
//} //default datetime showformater
dataRow.CreateCell(j).SetCellValue(DateTime.Parse(piValue.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
continue;
}
dataRow.CreateCell(j).SetCellValue(piValue.ToString());
}
++rowIndex;
}
//列宽自适应,只对英文和数字有效 这个动作比较耗时间
//for (int i = 0; i <= arrProperty.Length; ++i)
// sheet.AutoSizeColumn(i);
workbook.Write(ms);
ms.Flush();
return ms.ToArray();
}
catch (Exception ex)
{
Log.loggeremail.Error("RenderDataTableToExcel Exception:"+ex.Message);
return null;
}
finally
{
ms.Close();
sheet = null;
headerRow = null;
workbook = null;
}
} public static void SaveListToExcel<T>(List<T> SourceList, List<String> filter, string filePath) where T : new()
{
XSSFWorkbook workbook = null;
ISheet sheet = null;
XSSFRow headerRow = null;
try
{
workbook = new XSSFWorkbook();
sheet = workbook.CreateSheet();
headerRow = (XSSFRow)sheet.CreateRow(); PropertyInfo[] arrProperty = RemoveFilterColumn<T>(filter); PropertyInfo pi = null;
for (int i = ; i < arrProperty.Length; i++)
{
pi = arrProperty[i];
headerRow.CreateCell(i).SetCellValue(GetPropertyDescription(pi));
} int rowIndex = ;
for (int i = ; i < SourceList.Count; i++)
{
XSSFRow dataRow = (XSSFRow)sheet.CreateRow(rowIndex);
for (int j = ; j < arrProperty.Length; j++)
{
pi = arrProperty[j];
object piValue = pi.GetValue(SourceList[i], null);
if (piValue == null)
{
dataRow.CreateCell(j).SetCellValue("");
continue;
}
Type pitype = pi.PropertyType;
if (pitype.Name.ToLower().Contains("nullable"))
{
pitype = Nullable.GetUnderlyingType(pitype);
}
//var rowNumberAttr = pi.GetCustomAttributes(typeof(Attribute), false);
//if (rowNumberAttr != null && rowNumberAttr.Length > 0)
//{
// dataRow.CreateCell(j).SetCellValue((i + 1).ToString());
// continue;
//}
if (pitype == typeof(bool))
{
dataRow.CreateCell(j).SetCellValue(Convert.ToBoolean(piValue) ? "是" : "否");
continue;
}
if (pitype.IsEnum)
{
dataRow.CreateCell(j).SetCellValue(EnumHelper.GetDescription(pitype, Convert.ToInt32(piValue)));
continue;
}
if (pitype == typeof(DateTime)
|| pitype == typeof(DateTime?))
{
//var showDateTimeAttr = pi.GetCustomAttributes(typeof(DateTimeFormatAttribute), false);
//if (showDateTimeAttr != null && showDateTimeAttr.Length > 0)
//{
// DateTime nowtime = DateTime.Parse(piValue.ToString());
// arrData[i + 1, j] = nowtime.ToString((showDateTimeAttr[0] as DateTimeFormatAttribute).DataFormatString);
// continue;
//} //default datetime showformater
dataRow.CreateCell(j).SetCellValue(DateTime.Parse(piValue.ToString()).ToString("yyyy-MM-dd HH:mm:ss"));
continue;
}
dataRow.CreateCell(j).SetCellValue(piValue.ToString());
}
++rowIndex;
}
//列宽自适应,只对英文和数字有效 这个动作比较耗时间
//for (int i = 0; i <= arrProperty.Length; ++i)
// sheet.AutoSizeColumn(i); using (var file = new FileStream(filePath, FileMode.Create))
{
workbook.Write(file);
file.Close();
file.Dispose();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
sheet = null;
headerRow = null;
workbook = null;
}
} /// <summary>
/// 创建一个excel
/// </summary>
/// <returns></returns>
public static XSSFWorkbook CreateXSSFWorkbook()
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
return xssfworkbook;
} /// <summary>
/// 创建一个sheet
/// </summary>
/// <param name="hssfworkbook">excel</param>
/// <param name="sheetName">sheet名称</param>
/// <param name="isFreezePane">是否存在冻结</param>
/// <param name="colSplit"></param>
/// <param name="rowSplit">行数</param>
/// <param name="leftmostColumn"></param>
/// <param name="topRow">顶上N行</param>
/// <returns></returns>
public static ISheet CreateSheet(XSSFWorkbook xssfworkbook, string sheetName, bool isFreezePane = false, int colSplit = , int rowSplit = , int leftmostColumn = , int topRow = )
{
ISheet sheet1 = xssfworkbook.CreateSheet(sheetName); if (isFreezePane)
{
sheet1.CreateFreezePane(colSplit, rowSplit, leftmostColumn, topRow);
} return sheet1;
} public static IRow CreateRow(ISheet sheet, int rowIndex)
{
IRow row = sheet.CreateRow(rowIndex);
return row;
} public static ICell CreateCell(XSSFWorkbook xssfworkbook, IRow row, int cellIndex, string cellValue, bool isLock = true)
{
ICell cell = row.CreateCell(cellIndex);
cell.SetCellValue(cellValue);
//加锁
var locked = xssfworkbook.CreateCellStyle();
locked.IsLocked = isLock;
cell.CellStyle = locked; return cell;
} public static ICellStyle LockedRow(XSSFWorkbook xssfworkbook)
{
var locked = xssfworkbook.CreateCellStyle();
locked.IsLocked = true;
return locked;
} public static ICellStyle UnLockedRow(XSSFWorkbook xssfworkbook)
{
var locked = xssfworkbook.CreateCellStyle();
locked.IsLocked = false;
return locked;
} /// <summary>
/// 获取单元格样式
/// </summary>
/// <param name="hssfworkbook">Excel操作类</param>
/// <param name="font">单元格字体</param>
/// <param name="fillForegroundColor">图案的颜色</param>
/// <param name="fillPattern">图案样式</param>
/// <param name="fillBackgroundColor">单元格背景</param>
/// <param name="ha">垂直对齐方式</param>
/// <param name="va">垂直对齐方式</param>
/// <returns></returns>
public static ICellStyle GetCellStyle(XSSFWorkbook hssfworkbook, IFont font, HSSFColor fillForegroundColor, FillPattern fillPattern, HSSFColor fillBackgroundColor, NPOI.SS.UserModel.HorizontalAlignment ha, VerticalAlignment va, bool hasBorder)
{
ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
cellstyle.FillPattern = fillPattern;
cellstyle.Alignment = ha;
cellstyle.VerticalAlignment = va;
if (fillForegroundColor != null)
{
cellstyle.FillForegroundColor = fillForegroundColor.Indexed;
}
if (fillBackgroundColor != null)
{
cellstyle.FillBackgroundColor = fillBackgroundColor.Indexed;
}
if (font != null)
{
cellstyle.SetFont(font);
}
if (hasBorder)
{
//有边框
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;
}
return cellstyle;
} /// <summary>
/// 合并单元格
/// </summary>
/// <param name="sheet">要合并单元格所在的sheet</param>
/// <param name="rowstart">开始行的索引</param>
/// <param name="rowend">结束行的索引</param>
/// <param name="colstart">开始列的索引</param>
/// <param name="colend">结束列的索引</param>
public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
{
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
sheet.AddMergedRegion(cellRangeAddress);
} /// <summary>
/// 建立下拉,验证数据有效性
/// </summary>
/// <param name="hssfworkbook"></param>
/// <param name="sheet"></param>
/// <param name="firstRow"></param>
/// <param name="lastRow"></param>
/// <param name="firstCol"></param>
/// <param name="lastCol"></param>
/// <param name="refersToFormula"></param>
/// <param name="XSSFName"></param>
public static void SetValidationData(XSSFWorkbook hssfworkbook, ISheet sheet, int firstRow, int lastRow, int firstCol, int lastCol, string refersToFormula, string XSSFName)
{
//数据有效性 下拉
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet as XSSFSheet);
//位置
CellRangeAddressList regions = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); XSSFName range = (XSSFName)hssfworkbook.CreateName();
range.RefersToFormula = refersToFormula;
range.NameName = XSSFName;
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)dvHelper.CreateFormulaListConstraint(XSSFName); XSSFDataValidation dataValidate = (XSSFDataValidation)dvHelper.CreateValidation(dvConstraint, regions);
sheet.AddValidationData(dataValidate);
}

调用:

List<String> filter = new List<string>();
filter.Add("LableBatchNo");//过滤列
byte[] byteList = ExcelHelper.RenderToExcel<SecurityLabelModel>(allList, filter);
MemoryStream stream = new MemoryStream(byteList);
stream.Seek(, ); return new FileStreamResult(stream, "application/vnd.ms-excel") { FileDownloadName = HttpUtility.UrlPathEncode(名称 + DateTime.Now.ToString("yyyyMMddHHmmssfff") + 后缀) };

c# NPOI文件操作的更多相关文章

  1. 对Aspose.Cells Excel文件操作的扩展

    工作中对Excel操作的需求很是常见,今天其他项目组的同事在进行Excel数据导入时,使用Aspose.Cells Excel 遇到了些问题. 刚好闲来不忙,回想自己用过的Excel文件操作,有NPO ...

  2. 【.NET深呼吸】Zip文件操作(1):创建和读取zip文档

    .net的IO操作支持对zip文件的创建.读写和更新.使用起来也比较简单,.net的一向作风,东西都准备好了,至于如何使用,请看着办. 要对zip文件进行操作,主要用到以下三个类: 1.ZipFile ...

  3. 野路子出身PowerShell 文件操作实用功能

    本文出处:http://www.cnblogs.com/wy123/p/6129498.html 因工作需要,处理一批文件,本想写C#来处理的,后来想想这个是PowerShell的天职,索性就网上各种 ...

  4. Node基础篇(文件操作)

    文件操作 相关模块 Node内核提供了很多与文件操作相关的模块,每个模块都提供了一些最基本的操作API,在NPM中也有社区提供的功能包 fs: 基础的文件操作 API path: 提供和路径相关的操作 ...

  5. 归档NSKeyedArchiver解归档NSKeyedUnarchiver与文件管理类NSFileManager (文件操作)

    ========================== 文件操作 ========================== 一.归档NSKeyedArchiver 1.第一种方式:存储一种数据. // 归档 ...

  6. SQL Server附加数据库报错:无法打开物理文件,操作系统错误5

    问题描述:      附加数据时,提示无法打开物理文件,操作系统错误5.如下图: 问题原因:可能是文件访问权限方面的问题. 解决方案:找到数据库的mdf和ldf文件,赋予权限即可.如下图: 找到mdf ...

  7. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  8. Linux文件操作的主要接口API及相关细节

    操作系统API: 1.API是一些函数,这些函数是由linux系统提供支持的,由应用层程序来使用,应用层程序通过调用API来调用操作系统中的各种功能,来干活 文件操作的一般步骤: 1.在linux系统 ...

  9. C语言的fopen函数(文件操作/读写)

    头文件:#include <stdio.h> fopen()是一个常用的函数,用来以指定的方式打开文件,其原型为:    FILE * fopen(const char * path, c ...

随机推荐

  1. HTML5之contenteditable可编辑属性

    运用contenteditable实现输入框高度自动增加,输入框标题name相对高度自动居中,代码如下: <!DOCTYPE html> <html> <head> ...

  2. 多项式乘法,sb题

    给定一个n,输出\((a1+x)*(a2+x)*...(an+x)\)的多项式长度. 每一个字符(包括"a"."x"."(".") ...

  3. 第12组 Alpha事后诸葛亮

    Header 组长博客 Postmortem 设想和目标 我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? 要解决的是喜欢记录分享旅游生活的人群的行迹记录和分享问题, ...

  4. 【POJ2993】Emag eht htiw Em Pleh

    题目传送门 本题知识点:模拟(如果对国际象棋不熟悉的同学可以先百度一下) 本题跟POJ2996是逆过来的操作,如果做过[POJ2996]的同学就不会对题意不理解的了. (以下默认您已AC[POJ299 ...

  5. spring boot validation参数校验

    对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证. Spring Boot自身对数据在服务端的校验有一个比较好的支持,它能将 ...

  6. Windows本地搭建Edusoho环境

    Windows搭建Edusoho比Linux还要轻松的多.因为有很多环境集成工具如xampp.wampserver.phpstudy等.基本上安装号wampserver工具,直接将edusoho项目扔 ...

  7. 剑指offer:和为S的两个数字

    题目描述: 输入一个递增排序的数组和一个数字S,在数组中查找两个数,使得他们的和正好是S,如果有多对数字的和等于S,输出两个数的乘积最小的. 输出描述: 对应每个测试案例,输出两个数,小的先输出. 思 ...

  8. windows命令行查看文件MD5

    certutil -hashfile D:\1.exe MD5certutil -hashfile D:\1.exe SHA1certutil -hashfile D:\1.exe SHA256 原文 ...

  9. Xamarin图表开发基础教程(4)OxyPlot框架

    Xamarin图表开发基础教程(4)OxyPlot框架 XamaminAndroid中绘制线图OxyPlotAndroidDemo [示例1-1:OxyPlotAndroidDemo]下面实现线图的绘 ...

  10. WebGL调试工具分享

    学习WebGL,我们需要一些好用的调试工具,下面分享3个常用的调试工具. WebGL Inspector 下载地址:https://github.com/benvanik/WebGL-Inspecto ...