using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NPOI.SS.Util; namespace POICommen
{
public class NpoiHelper
{
#region 属性 private readonly int _perSheetCount = ; //每个sheet要保存的条数 public NpoiHelper()
{
} /// <summary>
/// 最大接收5万条每页,大于5万时,使用系统默认的值(4万)
/// </summary>
/// <param name="perSheetCounts"></param>
public NpoiHelper(int perSheetCounts)
{
if (_perSheetCount <= )
_perSheetCount = perSheetCounts;
} #endregion #region IExcelProvider 成员 public DataTable Import(Stream fs, string ext, out string msg, List<string> validates = null)
{
msg = string.Empty;
var dt = new DataTable();
try
{
IWorkbook workbook;
if (ext == ".xls")
workbook = new HSSFWorkbook(fs);
else
workbook = new XSSFWorkbook(fs);
const int num = ;
var sheet = workbook.GetSheetAt(num);
dt.TableName = sheet.SheetName;
var rowCount = sheet.LastRowNum;
const int firstNum = ;
var headerRow = sheet.GetRow();
int cellCount = headerRow.LastCellNum;
if (validates != null)
{
var validateCount = validates.Count;
if (validateCount > cellCount)
{
msg = "上传EXCEL文件格式不正确";
return null;
}
for (var i = ; i < validateCount; i++)
{
var columnName = headerRow.GetCell(i).StringCellValue;
if (validates[i] == columnName) continue;
msg = "上传EXCEL文件格式不正确";
return null;
}
}
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
var column = new DataColumn(headerRow.GetCell(i).StringCellValue);
dt.Columns.Add(column);
}
for (var i = firstNum + ; i <= rowCount; i++)
{
var row = sheet.GetRow(i);
var dataRow = dt.NewRow();
if (row != null)
for (int j = row.FirstCellNum; j < cellCount; j++)
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j), ext);
dt.Rows.Add(dataRow);
}
return dt;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} private static IFont GetFont(IWorkbook workbook, HSSFColor color)
{
var font = workbook.CreateFont();
font.Color = color.Indexed;
font.FontHeightInPoints = ;
font.Boldweight = ;
//font.FontName = "楷体";
font.IsItalic = true;
return font;
} public static void SetCellValues(ICell cell, string cellType, string cellValue)
{
switch (cellType)
{
case "System.String": //字符串类型
double result;
if (double.TryParse(cellValue, out result))
cell.SetCellValue(result);
else
cell.SetCellValue(cellValue);
break;
case "System.DateTime": //日期类型
DateTime dateV;
DateTime.TryParse(cellValue, out dateV);
cell.SetCellValue(dateV);
break;
case "System.Boolean": //布尔型
bool boolV;
bool.TryParse(cellValue, out boolV);
cell.SetCellValue(boolV);
break;
case "System.Int16": //整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV;
int.TryParse(cellValue, out intV);
cell.SetCellValue(intV);
break;
case "System.Decimal": //浮点型
case "System.Double":
double doubV;
double.TryParse(cellValue, out doubV);
cell.SetCellValue(doubV);
break;
case "System.DBNull": //空值处理
cell.SetCellValue("");
break;
default:
cell.SetCellValue("");
break;
}
} public string Export(string excelFileName, DataTable dtIn)
{
var workbook = new HSSFWorkbook();
ICell cell;
var sheetCount = ; //当前的sheet数量
var currentSheetCount = ; //循环时当前保存的条数,每页都会清零 //表头样式
var style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
var green = new HSSFColor.Green();
style.SetFont(GetFont(workbook, green)); //内容样式
style = workbook.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
var blue = new HSSFColor.Blue();
style.SetFont(GetFont(workbook, blue)); var sheet = workbook.CreateSheet("Sheet" + sheetCount);
//填充表头
var row = sheet.CreateRow();
for (var i = ; i < dtIn.Columns.Count; i++)
{
cell = row.CreateCell(i);
cell.SetCellValue(dtIn.Columns[i].ColumnName);
cell.CellStyle = style;
}
//填充内容
for (var i = ; i < dtIn.Rows.Count; i++)
{
if (currentSheetCount >= _perSheetCount)
{
sheetCount++;
currentSheetCount = ;
sheet = workbook.CreateSheet("Sheet" + sheetCount);
}
row = sheetCount == ? sheet.CreateRow(currentSheetCount + ) : sheet.CreateRow(currentSheetCount);
currentSheetCount++;
for (var j = ; j < dtIn.Columns.Count; j++)
{
cell = row.CreateCell(j);
cell.CellStyle = style;
SetCellValues(cell, dtIn.Columns[j].DataType.ToString(), dtIn.Rows[i][j].ToString());
}
}
var fs = new FileStream(excelFileName, FileMode.CreateNew, FileAccess.Write);
workbook.Write(fs);
fs.Close();
return excelFileName;
} public DataTable Import(string filepath, string key, string sheetName, string endKey)
{
var table = new DataTable();
try
{
using (var excelFileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
var file = Path.GetExtension(filepath);
if (file != null)
{
var type = file.Replace(".", "");
IWorkbook workbook;
if (type == "xls")
workbook = new HSSFWorkbook(excelFileStream);
else
workbook = new XSSFWorkbook(excelFileStream); for (var num = ; num < workbook.NumberOfSheets; num++)
{
var sheet = workbook.GetSheetAt(num);
if (sheet.SheetName != sheetName)
continue;
table.TableName = sheet.SheetName;
var rowCount = sheet.LastRowNum;
IRow headerRow = null;
var cellCount = ;
var firstNum = ; for (var i = ; i <= rowCount; i++)
{
if (sheet.GetRow(i).GetCell().StringCellValue != key) continue;
headerRow = sheet.GetRow(i);
cellCount = headerRow.LastCellNum;
firstNum = i;
break;
} //列名 //handling header.
if (headerRow != null)
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
var column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
} for (var i = firstNum + ; i <= rowCount; i++)
{
var row = sheet.GetRow(i);
var dataRow = table.NewRow();
var isEnd = false;
if (row != null)
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j), type);
if (dataRow[j].ToString() != endKey) continue;
isEnd = true;
break;
}
if (isEnd)
break;
table.Rows.Add(dataRow);
}
return table;
}
}
}
}
catch (Exception)
{
return null;
}
return table;
} private static string GetCellValue(ICell cell, string type)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.Blank:
return string.Empty;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
case CellType.Error:
return cell.ErrorCellValue.ToString();
case CellType.Numeric:
var format = cell.CellStyle.DataFormat;
if (format == || format == || format == || format == )
{
var date = cell.DateCellValue;
var re = date.ToString("yyy-MM-dd");
return re;
}
return cell.ToString(); case CellType.String:
return cell.StringCellValue; case CellType.Formula:
try
{
if (type == "xls")
{
var e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
else
{
var e = new XSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
}
catch
{
return cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
}
case CellType.Unknown:
return cell.ToString();
default:
return cell.ToString();
}
} #endregion #region 辅助导入 /// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="datatable"></param>
/// <returns></returns>
public IEnumerable<T> ConvertTo<T>(DataTable datatable) where T : new()
{
var temp = new List<T>();
try
{
var columnsNames =
(from DataColumn dataColumn in datatable.Columns select dataColumn.ColumnName).ToList();
temp = datatable.AsEnumerable().ToList().ConvertAll(row => GetObject<T>(row, columnsNames));
return temp;
}
catch
{
return temp;
}
} /// <summary>
/// 根据DataTable生成对象,对象的属性与列同名
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="row"></param>
/// <param name="columnsName"></param>
/// <returns></returns>
public T GetObject<T>(DataRow row, List<string> columnsName) where T : new()
{
var obj = new T();
try
{
var properties = typeof(T).GetProperties();
foreach (var objProperty in properties)
{
var attrs = objProperty.GetCustomAttributes(typeof(DisplayNameAttribute), false);
if (!attrs.Any()) continue;
var displayName = ((DisplayNameAttribute)attrs.First()).DisplayName; var columnname = columnsName.Find(s => s == displayName);
if (string.IsNullOrEmpty(columnname)) continue;
var value = row[columnname].ToString();
if (string.IsNullOrEmpty(value)) continue;
if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
{
value = row[columnname].ToString().Replace("$", "").Replace(",", "");
objProperty.SetValue(obj,
Convert.ChangeType(value,
Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
}
else
{
value = row[columnname].ToString().Replace("%", "");
objProperty.SetValue(obj,
Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
}
}
return obj;
}
catch
{
return obj;
}
} public static void CopyRow(int startRow, int endRow, int pPosition, ISheet sheet)
{
int pStartRow = startRow - ;
int pEndRow = endRow - ;
int targetRowFrom;
int targetRowTo;
int cloumnCount; CellRangeAddress region = null; if (pStartRow==-||pEndRow==-)
{
return;
} //拷贝合并的单元格
for (int k = ; k < sheet.NumMergedRegions; k++)
{
region = sheet.GetMergedRegion(k);
if (region.FirstRow>=pStartRow&&region.LastRow<=pEndRow)
{
targetRowFrom = region.FirstRow - pStartRow + pPosition;
targetRowTo = region.LastRow - pStartRow + pPosition;
CellRangeAddress newRegion = region.Copy();
newRegion.FirstRow = targetRowFrom;
newRegion.FirstColumn = region.FirstColumn;
newRegion.LastRow = targetRowTo;
newRegion.LastColumn = region.LastColumn;
sheet.AddMergedRegion(newRegion);
} } //设置列宽
for (int k = pStartRow; k <=pEndRow; k++)
{
IRow sourceRow = sheet.GetRow(k);
cloumnCount = sourceRow.LastCellNum;
if (sourceRow!=null)
{
IRow newRow = sheet.CreateRow(pPosition - pStartRow + k);
newRow.Height = sourceRow.Height;
for (int l = ; l < cloumnCount; l++)
{
ICell templateCell = sourceRow.GetCell(l);
if (templateCell!=null)
{
ICell newCell = newRow.CreateCell(l);
CopyCell(templateCell,newCell);
}
}
} } } private static void CopyCell(ICell srcCell, ICell distCell)
{
distCell.CellStyle=srcCell.CellStyle;
if (srcCell.CellComment!= null)
{
distCell.CellComment=srcCell.CellComment;
} CellType srcCellType = srcCell.CellType;
distCell.SetCellType(srcCellType); string cellValue = GetCellValue(srcCell, "xlsx");
SetCellValues(distCell, "System.String", cellValue);
} #endregion
}
}

NPOI helper的更多相关文章

  1. NPOI Helper文档

    public class ExcelHelper { /// <summary> /// NPOI Excel转DataTable /// </summary> /// < ...

  2. NPOI使用教程附Helper

    1 NPOI简介 1.1 NPOI是什么 NPOI是POI的.NET版本,POI是一套用Java写成的库,我们在开发中经常用到导入导出表格.文档的情况,NPOI能够帮助我们在没有安装微软Office的 ...

  3. NPOI 通用导出数据到Excel 分类: C# Helper 2014-11-04 16:06 246人阅读 评论(0) 收藏

    应用场景: 在项目中,经常遇到将数据库数据导出到Excel,针对这种情况做了个程序封装.工作原理:利用NPOI将SQL语句查询出的DataTable数据导出到Excel,所见即所得. 程序界面:   ...

  4. 用NPOI从DataBase到Excel '2

    NPOI的C# Helper代码2 public static MemoryStream ExportXls(DataTable dt) { HSSFWorkbook wk = new HSSFWor ...

  5. 用NPOI从DataBase到Excel

    NPOI的C# Helper代码 public static void WriteExcel(DataTable dt, string filePath) { ) { HSSFWorkbook wk ...

  6. NPOI分层导出

    using NPOI.HSSF.UserModel; using NPOI.POIFS.FileSystem; using org.in2bits.MyXls; using System; using ...

  7. NPOI导入,导出

    概述 NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目.NPOI 可以在没有安装 Office 或者相应环境的机器上对 WO ...

  8. NPOI导出Excel表功能实现(多个工作簿)(备用)

    Excel生成操作类: 代码 using System; using System.Collections.Generic; using System.Text; using System.IO; u ...

  9. ASP.NET中的Excel操作(NPOI方式)

    代码准备: 一:实体准备 代码如下: /// <summary> /// 一个能添加到将要导出到指定行的实体类型规范 /// data:{int StartColIndex ? 0, in ...

随机推荐

  1. 关于mybatis配置文件mapper传int值的问题

    1.首先看mapper代码,这是个更新语句. <set> <if test="sendmode!='' && sendmode!=null"> ...

  2. Delphi7连接MySql数据库-DBGrid控件显示数据

    一个简单的Delphi7小程序,使用MySql数据库做简单查询,用DBGrid控件显示结果,实现过程如下: (1)在MySql中新建demouser表,插入记录用于测试. (2)在Delphi7中新建 ...

  3. 神州数码NAT地址转换配置

    实验要求:熟练掌握NAT地址转换的配置方法 拓扑如下 R1 enable 进入特权模式 config 进入全局模式 hostname R1 修改名称 interface s0/1 进入端口 ip ad ...

  4. Xcode注释转文档appledoc使用

    参考了一些大神的方法总算成功了记录一下少走弯路 1:安装appledoc 使用终端下载: 命令行: git clone git://github.com/tomaz/appledoc.git cd . ...

  5. git教程:添加远程仓库

    转自: 添加远程仓库 现在的情景是,你已经在本地创建了一个Git仓库后,又想在GitHub创建一个Git仓库,并且让这两个仓库进行远程同步,这样,GitHub上的仓库既可以作为备份,又可以让其他人通过 ...

  6. 安装Feflow遇取的问题

    http://www.feflowjs.org/zh-cn/docs/ 在安装 npm install -g feflow-cli 是遇到这要一个问题 i C:\Program Files (x86) ...

  7. [LeetCode&Python] Problem 704. Binary Search

    Given a sorted (in ascending order) integer array nums of n elements and a target value, write a fun ...

  8. Golang微服务:micro实践

    micro 使用 工具安装 使用protoc生成代码,依赖两个插件:protoc-gen-go.protoc-gen-micro micro 工具 go get -u github.com/micro ...

  9. oracle数据库连接缓慢

    今天连接数据库时非常的慢,大概将近1分钟,才能连上,感觉不对,登录数据库所在的服务器,进行检查,常规的内存.硬盘.CPU全都正常,然后想要进入oracle用户时报错了:su: cannot set u ...

  10. 【译著】Code First :使用Entity. Framework编程(5)

    第五章 对数据库映射使用默认规则与配置 到目前为止我们已经领略了Code First的默认规则与配置对属性.类间关系的影响.在这两个领域内,Code First不仅影响模型也影响数据库.在这一章,你将 ...