ExcelUtility 类库经过我(梦在旅途)近期不断的优化与新增功能,现已基本趋向稳定,功能上也基本可以满足绝大部份的EXCEL导出需求,该类库已在我们公司大型ERP系统全面使用,效果不错,今天应用户的特殊需求,我又新增了一个功能,导出时动态生成多Sheet EXCEL。 ...
ExcelUtility 类库经过我(梦在旅途)近期不断的优化与新增功能,现已基本趋向稳定,功能上也基本可以满足绝大部份的EXCEL导出需求,该类库已在我们公司大型ERP系统全面使用,效果不错,今天应用户的特殊需求,我又新增了一个功能,导出时动态生成多Sheet EXCEL。
新增方法一:由GetFormatterContainer Func委托导出基于EXCEL模板的多Sheet文件,方法定义如下:
/// <summary> /// 由GetFormatterContainer Func委托导出基于EXCEL模板的多工作薄文件 /// </summary> /// <typeparam name="T">数据源可枚举项类型</typeparam> /// <param name="templatePath">模板路径</param> /// <param name="sheetName">模板中使用的工作薄名称</param> /// <param name="dataSource">数据源</param> /// <param name="getFormatterContainer">生成模板数据格式化容器(SheetFormatterContainer)委托,在委托方法中实现模板的格式化过程</param> /// <param name="sheetSize">每个工作薄显示的数据记录数</param> /// <param name="filePath">导出路径,可选</param> /// <returns></returns> public static string ToExcelWithTemplate<T>(string templatePath, string sheetName, IEnumerable<T> dataSource, Func<IEnumerable<T>, SheetFormatterContainer> getFormatterContainer, int sheetSize, string filePath = null) { if (!File.Exists(templatePath)) { throw new FileNotFoundException(templatePath + "文件不存在!"); } bool isCompatible = Common.GetIsCompatible(templatePath); if (string.IsNullOrEmpty(filePath)) { filePath = Common.GetSaveFilePath(isCompatible); } else if (isCompatible && !Path.GetExtension(filePath).Equals(".xls", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("当模板采用兼容模式时(低版本格式,如:xls,xlt),则指定的导出文件格式必需为xls。"); } if (string.IsNullOrEmpty(filePath)) return null; int sheetCount = 0; var formatterContainers = new Dictionary<string, SheetFormatterContainer>(); IEnumerable<T> data = null; while ((data = dataSource.Take(sheetSize)).Count() > 0) { var sheetFormatterContainer = getFormatterContainer(data); sheetCount++; if (sheetCount == 1) { formatterContainers.Add(sheetName, sheetFormatterContainer); } else { formatterContainers.Add(sheetName + sheetCount.ToString(), sheetFormatterContainer); } dataSource = dataSource.Skip(sheetSize); } string temp_templatePath = null; try { temp_templatePath = Common.CreateTempFileByTemplate(templatePath, sheetName, sheetCount); filePath = ToExcelWithTemplate(temp_templatePath, formatterContainers, filePath); } finally { if (!string.IsNullOrEmpty(temp_templatePath) && File.Exists(temp_templatePath)) { File.Delete(temp_templatePath); } string temp_templateConfigFilePath = Path.ChangeExtension(temp_templatePath, ".
原标题:分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续3篇
关键词:excel
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。