从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:\新房媒体-C端收款.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);
        //}

}

时间: 2024-11-05 07:14:44

从excel文件中获取数据(2)的相关文章

从excel文件中获取数据 转化成list集合 并去重

static void Main(string[] args)        {            string filepath = @"E:\新房媒体-C端收款.xlsx"; //IReadEntDataFromExcel iReadEntDataFromExcel = new  ReadEntDataFromExcelInfo();            //List<String> result=iReadEntDataFromExcel.ReadEntData

[Python]将Excel文件中的数据导入MySQL

Github Link 需求 现有2000+文件夹,每个文件夹下有若干excel文件,现在要将这些excel文件中的数据导入mysql. 每个excel文件的第一行是无效数据. 除了excel文件中已有的数据,还要添加一列,名为“at_company”,值为821. 流程 (1)获取excel文件列表,并根据excel文件名确定之后需要创建的table名: (2)连接mysql (3)创建table (4)插入数据 (5)断开连接 依赖模块 1. xlrd # to read excel fil

用python读取带密码的excel文件中的数据

用python读取带密码的excel文件中的数据,程序代码如下: #filename:readingxls.py ''' 此程序的作用为:用python读取带密码的excel文件中的数据. 首先通过pip安装xlrd第三方库 pip3 install xlrd 请输入excel文件路径:D:\x1.xls ''' import xlrd path=input("请输入excel文件路径:") workbook=xlrd.open_workbook(path) b=len(workboo

springMVC从上传的Excel文件中读取数据

示例:导入客户文件(Excle文件) 一.编辑customer.xlsx 二.编辑jsp(addCustomer3.jsp) <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefi

python从Microsoft Excel文件中导入数据

excel中后缀为csv和xls,二者区别如下:1.xls 文件就是Microsoft excel电子表格的文件格式.2.csv是最通用的一种文件格式,它可以非常容易地被导入各种PC表格及数据库中. 此文件,一行即为数据表的一行.生成数据表字段用半角逗号隔开.csv是文本文件,用记事本就能打开,XLS是二进制的文件只有用EXCEL才能打csv文件是以逗号为分隔符号,将各字段列分离出的一种ASCII文件.csv(*.csv) 文件格式只能保存活动工作表中的单元格所显示的文本和数值.工作表中所有的数

Java读写Excel文件中数据的简便方法

Java开发项目中经常会碰到处理Excel文件中数据的情况,这里通过一个例子来看一下实现方法:从Excel文件orders.xls中读取订单信息,从中找出2010年1月1日(含)之后,并且SELLERID等于18的订单.找到的数据写入order_result.xls文件. Excel文件orders.xls的内容如下: ORDERID CLIENT SELLERID AMOUNT ORDERDATE 1 UJRNP 17 392 2008/11/2 15:28 2 SJCH 6 4802 200

C#创建Excel文件并将数据导出到Excel文件

C#创建Excel文件,这里实际上是从资源中提取一个事先创建好的Excel文件,文件提取成功后,使用OleDb方法连接Excel,向Excel文件中写入数据. 创建解决方案 菜单>新建>项目>Windows窗体应用程序: 添加相关组件: 添加两个DataGridView,一个TextBox,两个按钮 ,如下图: 添加Excel资源: 先在文件夹中新建一个Excel文件,在Sheet1表的第一行设置列名: 双击"Resources.resx"文件打开资源文件视图: 添加

效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】) 转

效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中[附源代码下载])  本文目录: (一)背景 (二)数据库数据导入到Excel的方法比较   (三)SSIS的简介   (四)数据库中存储过程示例(SSIS应用需要) (五)Excel模板的制作(这步这么简单,稍微介绍一下)   (六)SSIS操作过程(生成Package,用来调用)(下一篇随笔将详细讲解制作Package包的过程,图片太多,篇幅过长,因此本文将直接采用生成的Package包进行

(2) 如何用Apache POI操作Excel文件-----如何在已有的Excel文件中插入一行新的数据?

在POI的第一节入门中,我们提供了两个简单的例子,一个是如何用Apache POI新建一个工作薄,另外一个例子是,如果用Apache POI新建一个工作表.那么在这个章节里面,我将会给大家演示一下,如何用Apache POI在已有的Excel文件中插入一行新的数据.具体代码,请看下面的例子. import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.