nuget添加npoi

    /// <summary>
/// npoi帮助类
/// </summary>
public static class NpoiHelper
{
/// <summary>
/// 根据文件路径,获取表格集合
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static List<DataTable> GetDataTableList(string filePath)
{
var list = new ConcurrentBag<DataTable>(); using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
var isExcel2007 = filePath.IsExcel2007();
var workBook = stream.GetWorkbook(isExcel2007);
var sheetIndexList = new List<int>();
for (int i = ; i < workBook.NumberOfSheets; i++) sheetIndexList.Add(i);
Parallel.ForEach(sheetIndexList, new ParallelOptions
{
MaxDegreeOfParallelism =
}, (source, state, index) =>
{
try
{
if (!workBook.IsSheetHidden(source))
list.Add(GetDataTableToY(workBook, source));
}
catch (NPOI.POIFS.FileSystem.OfficeXmlFileException nopiEx)
{
Console.WriteLine($"SheetIndex:{index}\t\tException:{nopiEx.Message}");
}
catch (Exception e)
{
Console.WriteLine(e);
}
});
} return list.ToList();
} /// <summary>
/// 根据sheet索引,把数据转换为datatable,以Y轴为准
/// </summary>
/// <param name="workBook"></param>
/// <param name="sheetIndex">sheet索引</param>
/// <param name="validRowIndex"></param>
/// <returns></returns>
public static DataTable GetDataTableToY(IWorkbook workBook, int sheetIndex, int validRowIndex = )
{
var sheet = workBook.GetSheetAt(sheetIndex);
var table = new DataTable(sheet.SheetName); // 设置最大列,默认为1
var maxColumnNum = ;
// 不是有效列集合,连续超过三行不读取后续所有列
var noValidColumnList = new List<int>();
// 列:按照列把数据填充到datatable中,防止无限列出现
for (var columnIndex = ; columnIndex < maxColumnNum; columnIndex++)
{
var column = new DataColumn();
table.Columns.Add(column);
noValidColumnList.Add(columnIndex);
// 列中所有数据都是null为true
var isAllEmpty = true;
// 行
for (var rowIndex = ; rowIndex < sheet.LastRowNum; rowIndex++)
{
if (columnIndex == ) table.Rows.Add(table.NewRow());
var itemRow = sheet.GetRow(rowIndex);
if (itemRow == null) continue;
maxColumnNum = maxColumnNum < itemRow.LastCellNum ? itemRow.LastCellNum : maxColumnNum;
// 把格式转换为utf-8
var itemCellValue = itemRow.GetValue(columnIndex).FormatUtf8String();
if (!itemCellValue.IsNullOrWhiteSpace()) isAllEmpty = false;
table.Rows[rowIndex][columnIndex] = itemCellValue;
} // 当前列有值
if (!isAllEmpty)
noValidColumnList.Clear();
// 连续空白列超过三行 或 有空白行且当前行为最后一行
else if (noValidColumnList.Count > || (noValidColumnList.Count > && columnIndex == maxColumnNum - ))
{
for (var i = noValidColumnList.Count - ; i >= ; i--)
table.Columns.RemoveAt(noValidColumnList[i]);
break;
}
}
// 得到一个sheet中有多少个合并单元格
int sheetMergeCount = sheet.NumMergedRegions;
for (var i = ; i < sheetMergeCount; i++)
{
// 获取合并后的单元格
var range = sheet.GetMergedRegion(i);
sheet.IsMergedRegion(range);
var cellValue = string.Empty;
for (var mRowIndex = range.FirstRow; mRowIndex <= range.LastRow; mRowIndex++)
{
for (var mColumnIndex = range.FirstColumn; mColumnIndex <= range.LastColumn; mColumnIndex++)
{
var itemCellValue = table.Rows[range.FirstRow][range.FirstColumn].FormatUtf8String();
if (!itemCellValue.IsNullOrWhiteSpace())
cellValue = itemCellValue;
table.Rows[mRowIndex][mColumnIndex] = cellValue;
}
}
} return table;
} #region 公共方法 /// <summary>
/// 判断excel是否是2007版本:.xls
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static bool IsExcel2007(this string filePath)
{
return Path.GetExtension(filePath)?.ToLower() == ".xls";
} /// <summary>
/// 根据版本创建IWorkbook对象
/// </summary>
/// <param name="stream"></param>
/// <param name="isExcel2007"></param>
/// <returns></returns>
public static IWorkbook GetWorkbook(this Stream stream, bool isExcel2007)
{
return isExcel2007 ? (IWorkbook)new HSSFWorkbook(stream) : new XSSFWorkbook(stream);
}
/// <summary>
/// 获取XSSFRow的值(全部统一转成字符串)
/// </summary>
/// <param name="row"></param>
/// <param name="index"></param>
/// <returns></returns>
public static string GetValue(this IRow row, int index)
{
var rowCell = row.GetCell(index);
return GetValueByCellStyle(rowCell, rowCell?.CellType);
} /// <summary>
/// 根据单元格的类型获取单元格的值
/// </summary>
/// <param name="rowCell"></param>
/// <param name="type"></param>
/// <returns></returns>
public static string GetValueByCellStyle(ICell rowCell, CellType? type)
{
string value = string.Empty;
switch (type)
{
case CellType.String:
value = rowCell.StringCellValue;
break;
case CellType.Numeric:
if (DateUtil.IsCellInternalDateFormatted(rowCell))
{
value = DateTime.FromOADate(rowCell.NumericCellValue).ToString();
}
else if (DateUtil.IsCellDateFormatted(rowCell))
{
value = DateTime.FromOADate(rowCell.NumericCellValue).ToString();
}
//有些情况,时间搓?数字格式化显示为时间,不属于上面两种时间格式
else if (rowCell.CellStyle.GetDataFormatString() == null)
{
value = DateTime.FromOADate(rowCell.NumericCellValue).ToString();
}
else if (rowCell.CellStyle.GetDataFormatString().Contains("$"))
{
value = "$" + rowCell.NumericCellValue.ToString();
}
else if (rowCell.CellStyle.GetDataFormatString().Contains("¥"))
{
value = "¥" + rowCell.NumericCellValue.ToString();
}
else if (rowCell.CellStyle.GetDataFormatString().Contains("¥"))
{
value = "¥" + rowCell.NumericCellValue.ToString();
}
else if (rowCell.CellStyle.GetDataFormatString().Contains("€"))
{
value = "€" + rowCell.NumericCellValue.ToString();
}
else
{
value = rowCell.NumericCellValue.ToString();
}
break;
case CellType.Boolean:
value = rowCell.BooleanCellValue.ToString();
break;
case CellType.Error:
value = ErrorEval.GetText(rowCell.ErrorCellValue);
break;
case CellType.Formula:
// TODO: 是否存在 嵌套 公式类型
value = GetValueByCellStyle(rowCell, rowCell?.CachedFormulaResultType);
break;
}
return value;
} #endregion }

NET npoi帮助类的更多相关文章

  1. NPOI 帮助类

    NPOI 帮助类 代码实现了来自于互联网 using System; using System.Data; using System.IO; using System.Text; using NPOI ...

  2. NPOI帮助类

    /// <summary> /// NPOI导出帮助类 /// </summary> public class NPOIHelper { /// <summary> ...

  3. NPOI Excel类

    using System;using System.Collections.Generic;using System.Linq;using System.Text;using NPOI.HSSF.Us ...

  4. NPOI操作类

    using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Secu ...

  5. NPOI帮助类(Excel转DataTable、DataTable转Excel)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using NPOI.SS. ...

  6. NPOI工具类

    NPOI调用方法 DataTable dt = new DataTable(); Dictionary<string, string> header = new Dictionary< ...

  7. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  8. 总结一下工作中遇到的NPOI以及在ASP.NET MVC中的使用

    1.前言 相信大家在工作中经常要遇到一些导入导出Execl操作.学习贵在分享,分享使人快乐,园子里的前辈已经有很多好的文章,鄙人也是能力有限,在这里把这些好的文章总结,方便以后再工作中使用. NPOI ...

  9. .NET使用NPOI组件将数据导出Excel

    .NPOI官方网站:http://npoi.codeplex.com/ 可以到此网站上去下载最新的NPOI组件版本 2.NPOI在线学习教程(中文版): http://www.cnblogs.com/ ...

随机推荐

  1. python 字符串占位符的使用

    name2='我是{} 我的专业是 {}'.format('张三','计算机科学技术')print(name2)

  2. oracle迁移

    #导出scott的数据,排除 table_a table_b expdp system/password schemas=scott directory=datadir dumpfile=scott_ ...

  3. CRC-32的原理和实现

    /* crc32.c -- compute the CRC-32 of a data stream * Copyright (C) 1995-2002 Mark Adler * For conditi ...

  4. C#中的String类2

    深入C# String类 C#中的String类 他是专门处理字符串的(String),他在System的命名空间下,在C#中我们使用的是string 小写的string只是大写的String的一个别 ...

  5. springboot xml声明式事务管理方案

    在开发过程中springboot提供的常见的事务解决方案是使用注解方式实现. 使用注解 在启动类上添加注解 @EnableTransactionManagement 在需要事务控制的方法添加@Tran ...

  6. 威伦TK6070iQ触摸屏的使用

    A.TK6070iQ只支持U盘互相倒腾. TK6070iQ有2个串口Com1 (232) Com2 (485) U盘上传 需要选择COM2(485),因为上传后是PLC与触摸屏通过485通讯,协议选s ...

  7. java socket之上传文件

    一.功能介绍 该功能主要实现,将客户端的:F:/work/socketSample/filetemp/client/test_client.txt上传到服务端F:/work/socketSample/ ...

  8. Spring Boot项目Maven Build报错的解决方法

    问题1, [ERROR]Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.21.0:test (defau ...

  9. Redis-环境搭建

    Redis官方不提供Windows版,不过微软开源组织提供了Windows版本的Redis,此处将安装Windows版的Reids,供学习使用. 1.下载Windows版Redis安装包: 安装包地址 ...

  10. 1、JavaScript 基础一 (从零学习JavaScript)

    1:定义:javascript是一种弱类型.动态类型.解释型的脚本语言. 弱类型:类型检查不严格,偏向于容忍隐式类型转换. 强类型:类型检查严格,偏向于不容忍隐式类型转换. 动态类型:运行的时候执行类 ...