从excel文件中获取数据(2)
本方法引用 Aspose.Cells.dll,ICSharpCode.SharpZipLib.dll ,NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,NPOI.OpenXmlFormats.dll
static void Main(string[] args)
{
string filepath = @"E:\我的.xlsx";
IReadEntDataFromExcel iReadEntDataFromExcel = new ReadEntDataFromExcelInfo();
List<String> result=iReadEntDataFromExcel.ReadEntDataFromExcel(filepath);
}
建一个类IReadEntDataFromExcel.cs:
public interface IReadEntDataFromExcel
{
List<string> ReadEntDataFromExcel(string filePath);
}
建一个类NOPIExcelHelper.cs :
public class NOPIExcelHelper
{
#region 单例定义
private static object lockObject = new object();
protected NOPIExcelHelper()
{
}
private static volatile NOPIExcelHelper _instance;
public static NOPIExcelHelper Instance
{
get
{
if (_instance == null)
{
lock (lockObject)
{
return _instance ?? (_instance = new NOPIExcelHelper());
}
}
return _instance;
}
}
#endregion 单例定义
public static DataSet ExcelToDataSet(string excelPath)
{
DataSet dataSet = new DataSet();
dataSet = ExcelToDataSet(excelPath, false);
return dataSet;
}
public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader)
{
int sheetCount;
return ExcelToDataSet(excelPath, firstRowAsHeader, out sheetCount);
}
public static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
{
sheetCount = 0;
using (DataSet ds = new DataSet())
{
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
if (Path.GetExtension(excelPath).ToLower() == ".xls".ToLower())
{
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
sheetCount = workbook.NumberOfSheets;
for (int i = 0; i < sheetCount; ++i)
{
HSSFSheet sheet = workbook.GetSheetAt(i) as HSSFSheet;
DataTable dt = ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
ds.Tables.Add(dt);
}
}
else if (Path.GetExtension(excelPath).ToLower() == ".xlsx".ToLower())
{
XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
sheetCount = workbook.NumberOfSheets;
for (int i = 0; i < sheetCount; ++i)
{
XSSFSheet sheet = workbook.GetSheetAt(i) as XSSFSheet;
DataTable dt = ExcelToDataTableX(sheet, evaluator, firstRowAsHeader);
ds.Tables.Add(dt);
}
}
}
return ds;
}
}
public static DataTable ExcelToDataTable(string excelPath, string sheetName)
{
return ExcelToDataTable(excelPath, sheetName, true);
}
public static DataTable ExcelToDataTable(string excelPath, string sheetName, bool firstRowAsHeader)
{
using (FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
HSSFSheet sheet = workbook.GetSheet(sheetName) as HSSFSheet;
return ExcelToDataTable(sheet, evaluator, firstRowAsHeader);
}
}
private static DataTable ExcelToDataTable(HSSFSheet sheet, HSSFFormulaEvaluator evaluator, bool firstRowAsHeader)
{
if (firstRowAsHeader)
{
return ExcelToDataTableFirstRowAsHeader(sheet, evaluator);
}
else
{
return ExcelToDataTable(sheet, evaluator);
}
}
private static DataTable ExcelToDataTableX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator, bool firstRowAsHeader)
{
if (firstRowAsHeader)
{
return ExcelToDataTableFirstRowAsHeaderX(sheet, evaluator);
}
else
{
return ExcelToDataTableX(sheet, evaluator);
}
}
private static DataTable ExcelToDataTableFirstRowAsHeader(HSSFSheet sheet, HSSFFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
HSSFRow firstRow = sheet.GetRow(0) as HSSFRow;
int cellCount = GetCellCount(sheet);
for (int i = 0; i < cellCount; i++)
{
if (firstRow.GetCell(i) != null)
{
dt.Columns.Add(firstRow.GetCell(i).ToString() ?? string.Format("F{0}", i + 1), typeof(string));
}
else
{
dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
}
}
for (int i = 1; i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i) as HSSFRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRow(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static DataTable ExcelToDataTableFirstRowAsHeaderX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
XSSFRow firstRow = sheet.GetRow(0) as XSSFRow;
int cellCount = GetCellCountX(sheet);
for (int i = 0; i < cellCount; i++)
{
if (firstRow.GetCell(i) != null)
{
dt.Columns.Add(firstRow.GetCell(i).ToString() ?? string.Format("F{0}", i + 1), typeof(string));
}
else
{
dt.Columns.Add(string.Format("F{0}", i + 1), typeof(string));
}
}
for (int i = 1; i <= sheet.LastRowNum; i++)
{
XSSFRow row = sheet.GetRow(i) as XSSFRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRowX(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static DataTable ExcelToDataTable(HSSFSheet sheet, HSSFFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
if (sheet.LastRowNum != 0)
{
int cellCount = GetCellCount(sheet);
for (int i = 0; i < cellCount; i++)
{
dt.Columns.Add(string.Format("F{0}", i), typeof(string));
}
for (int i = 0; i < sheet.FirstRowNum; ++i)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
{
HSSFRow row = sheet.GetRow(i) as HSSFRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRow(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static DataTable ExcelToDataTableX(XSSFSheet sheet, XSSFFormulaEvaluator evaluator)
{
using (DataTable dt = new DataTable())
{
if (sheet.LastRowNum != 0)
{
int cellCount = GetCellCountX(sheet);
for (int i = 0; i < cellCount; i++)
{
dt.Columns.Add(string.Format("F{0}", i), typeof(string));
}
for (int i = 0; i < sheet.FirstRowNum; ++i)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
{
XSSFRow row = sheet.GetRow(i) as XSSFRow;
DataRow dr = dt.NewRow();
FillDataRowByHSSFRowX(row, evaluator, ref dr);
dt.Rows.Add(dr);
}
}
dt.TableName = sheet.SheetName;
return dt;
}
}
private static void FillDataRowByHSSFRow(HSSFRow row, HSSFFormulaEvaluator evaluator, ref DataRow dr)
{
if (row != null)
{
for (int j = 0; j < dr.Table.Columns.Count; j++)
{
HSSFCell cell = row.GetCell(j) as HSSFCell;
if (cell != null)
{
switch (cell.CellType)
{
case CellType.Blank:
dr[j] = DBNull.Value;
break;
case CellType.Boolean:
dr[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
dr[j] = cell.DateCellValue;
}
else
{
dr[j] = cell.NumericCellValue;
}
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Error:
dr[j] = cell.ErrorCellValue;
break;
case CellType.Formula:
cell = evaluator.EvaluateInCell(cell) as HSSFCell;
dr[j] = cell.ToString();
break;
default:
throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
}
}
}
}
}
private static void FillDataRowByHSSFRowX(XSSFRow row, XSSFFormulaEvaluator evaluator, ref DataRow dr)
{
if (row != null)
{
for (int j = 0; j < dr.Table.Columns.Count; j++)
{
XSSFCell cell = row.GetCell(j) as XSSFCell;
if (cell != null)
{
switch (cell.CellType)
{
case CellType.Blank:
dr[j] = DBNull.Value;
break;
case CellType.Boolean:
dr[j] = cell.BooleanCellValue;
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
dr[j] = cell.DateCellValue;
}
else
{
dr[j] = cell.NumericCellValue;
}
break;
case CellType.String:
dr[j] = cell.StringCellValue;
break;
case CellType.Error:
dr[j] = cell.ErrorCellValue;
break;
case CellType.Formula:
cell = evaluator.EvaluateInCell(cell) as XSSFCell;
dr[j] = cell.ToString();
break;
default:
throw new NotSupportedException(string.Format("Catched unhandle CellType[{0}]", cell.CellType));
}
}
}
}
}
private static int GetCellCount(HSSFSheet sheet)
{
int firstRowNum = sheet.FirstRowNum;
int cellCount = 0;
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
{
HSSFRow row = sheet.GetRow(i) as HSSFRow;
if (row != null && row.LastCellNum > cellCount)
{
cellCount = row.LastCellNum;
}
}
return cellCount;
}
private static int GetCellCountX(XSSFSheet sheet)
{
int firstRowNum = sheet.FirstRowNum;
int cellCount = 0;
for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; ++i)
{
XSSFRow row = sheet.GetRow(i) as XSSFRow;
if (row != null && row.LastCellNum > cellCount)
{
cellCount = row.LastCellNum;
}
}
return cellCount;
}
}
建一个类ReadEntDataFromExcel.cs :
public class ReadEntDataFromExcelInfo : IReadEntDataFromExcel
{
#region 单例定义
private static object lockObject = new object();
public ReadEntDataFromExcelInfo()
{
}
private static volatile ReadEntDataFromExcelInfo _instance;
public static ReadEntDataFromExcelInfo Instance
{
get
{
if (_instance == null)
{
lock (lockObject)
{
return _instance ?? (_instance = new ReadEntDataFromExcelInfo());
}
}
return _instance;
}
}
#endregion 单例定义
//protected IWriteLogMess WriteLogMessProvider
//{
// get
// {
// return WriteLogMess.Instance;
// }
//}
public List<string> ReadEntDataFromExcel(string filePath)
{
//string filePath = @"E:\Table\企业征信存量数据名单表0630.xlsx";
List<string> result = null;
if (string.IsNullOrEmpty(filePath))
{
throw new ArgumentNullException("ReadEntDataFromExcel 参数为空");
}
try
{
result = this.ReadEntDataFromExcelProvider(filePath);
}
catch (Exception ex)
{
//this.WriteLogMessProvider.WritreLogExption(ex, "ReadEntDataFromExcelInfo/ReadEntDataFromExcel");
}
return result;
}
private List<string> ReadEntDataFromExcelProvider(string filePath)
{
NOPIExcelHelper NPOIHandler = NOPIExcelHelper.Instance;
DataSet dataSet = new DataSet();
dataSet = NOPIExcelHelper.ExcelToDataSet(filePath);
DataTable table = new DataTable();
foreach (DataTable datatable in dataSet.Tables)
{
table.Merge(datatable);
}
var hashset = new HashSet<string>();
foreach (DataRow dr in table.Rows)
{
hashset.Add(dr["F1"].ToString().Trim());
}
List<String> result = hashset.ToList();
return result;
}
//public static IList<T> ConvertTo<T>(DataTable table)
//{
// if (table == null)
// {
// return null;
// }
// IList<DataRow> rows = new List<DataRow>();
// foreach (DataRow row in table.Rows)
// {
// rows.Add(row);
// }
// return ConvertTo<T>(rows);
//}
}
从excel文件中获取数据(2)的更多相关文章
- [Python]将Excel文件中的数据导入MySQL
Github Link 需求 现有2000+文件夹,每个文件夹下有若干excel文件,现在要将这些excel文件中的数据导入mysql. 每个excel文件的第一行是无效数据. 除了excel文件中已 ...
- 用Python的pandas框架操作Excel文件中的数据教程
用Python的pandas框架操作Excel文件中的数据教程 本文的目的,是向您展示如何使用pandas 来执行一些常见的Excel任务.有些例子比较琐碎,但我觉得展示这些简单的东西与那些你可以在其 ...
- Java读取、写入、处理Excel文件中的数据(转载)
原文链接 在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对Excel中的数据进行读取操作,本文将介绍Excel读写的常用方法,希望对大家学习Java读写Ex ...
- SQLite从Excel文件中导入数据
元数据 另存为.csv格式 用记事本打开 打开后的数据 Android客户端开发的时候使用了SQLite数据库,为了测试,需要将一些excel文件中的数据导入到数据库的表中,下面是几个步骤: 数据库表 ...
- springMVC从上传的Excel文件中读取数据
示例:导入客户文件(Excle文件) 一.编辑customer.xlsx 二.在spring的xml文件设置上传文件大小 <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1 ...
- 用python的pandas读取excel文件中的数据
一.读取Excel文件 使用pandas的read_excel()方法,可通过文件路径直接读取.注意到,在一个excel文件中有多个sheet,因此,对excel文件的读取实际上是读取指定文件.并 ...
- python从Microsoft Excel文件中导入数据
excel中后缀为csv和xls,二者区别如下:1.xls 文件就是Microsoft excel电子表格的文件格式.2.csv是最通用的一种文件格式,它可以非常容易地被导入各种PC表格及数据库中. ...
- MATLAB读写Excel文件中的数据
读取: %读取filename文件中指定表的数据,存入dataRead矩阵中 dataRead=xlsread('filename.xls',sheet); 写入: %将矩阵dataWrite中的数据 ...
- matlab读取excel文件中的数据
1.读取sheet1中的所有数据 1.1首先我们建立一个sheet表,表名为‘111’ 1.2 默认这些文本以及数字都放在sheet1中,我们将此excel选入当前工作目录(必要步骤), 选入当前工作 ...
随机推荐
- DB2 中文排序问题
本地测试库中 代码集: GBK 数据库配置发行版级别 = 0x0c00 数据库发行版级别 = 0x0c00 数据库地域 = CN 数据库代码页 = 1386 数据库代码集 = GBK 数据库国家/地区 ...
- 服务 在初始化安装时发生异常:System.IO.FileNotFoundException: "file:///D:\testService"未能加载文件或程序集。系统找不到指定文件。
@echo.@if exist "%windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe" goto INSTALL ...
- Android SQLite 通配符查询找不到参数问题
使用Android SQLite中SQLiteDatabase类的query方法查询时,如果where中包含通配符,则参数会无法设置,如类似下面的方法查询时 SQLiteDatabase db = d ...
- urllib2抓取HTML存入Excel
通过urllib2抓取HTML网页,然后过滤出包含特定字符的行,并写入Excel文件: # -*- coding: utf-8 -*- import sys #import urllib import ...
- Tomcat服务器重启失败:The server may already be running in another process, or a system process may be using the port.
在控制台重启Tomcat服务器,报错如下: 原因分析: You've another instance of Tomcat already running. You can confirm this ...
- c++中处理输入输出的方法
============ 怎么处理一行空格中的逗号, ,,, ,,, ,,, c,c,d,d 使用c++的方法,可以这么处理: #include <sstream> #include< ...
- Node.js的循环与异步问题
(转自:http://bbs.tianya.cn/post-itinfo-280080-1.shtml) Node.js 的异步机制由事件和回调函数实现,一开始接触可能会感觉违反常规,但习惯 以后就会 ...
- interview que
百度: MySQL InnoDB存储的文件结构 索引树是如何维护的? 数据库自增主键可能的问题 Redis的并发竞争问题如何解决了解Redis事务的CAS操作吗 分析线程池的实现原理和线程的调度过程 ...
- unity自定义菜单面板开发
using UnityEditor;using UnityEngine;using CreateTerrainDLL; public class CreateTerrainMenu : EditorW ...
- linux svn 用户配置
1:创建存放仓库的目录 mkdir -p /home/svn/ 2:创建svn仓库 svnadmin create /home/svn/evansource 3:配置仓库(一共三个文件夹auzhz.p ...