码迷,mamicode.com
首页 > 其他好文 > 详细

NPOI 辅助类

时间:2015-10-26 15:11:11      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace 简易入库程序
{
    public class ExcleCore
    {
        private IWorkbook _workbook;
        private string _filePath;
        public List<string> GetSheetNames { get; set; }
        public List<string> SheetNames { get; set; }

        public ExcleCore(string filePath)
        {
            SheetNames = new List<string>();
            _filePath = filePath;
            LoadFile();
        }

        #region Excel信息

        /// <summary>
        /// 获取Excel信息
        /// </summary>
        /// <param name="filePath"></param>
        public List<string> LoadFile()
        {
            var prevCulture = Thread.CurrentThread.CurrentCulture;
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
 
            SheetNames = new List<string>();
            string fileExt = Path.GetExtension(_filePath);
            using (var fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                //根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
                //根据后缀不同,决定实例化对象
                if (fileExt == ".xls")
                {
                    HSSFWorkbook workbook = new HSSFWorkbook(fs);
                    _workbook = workbook;
                    int x = workbook.Workbook.NumSheets;
                    List<string> sheetNames = new List<string>();
                    for (int i = 0; i < x; i++)
                    {

                        SheetNames.Add(workbook.Workbook.GetSheetName(i));
                    }
                }
                else if (fileExt == ".xlsx")
                {
                    XSSFWorkbook workbook = new XSSFWorkbook(fs);
                    _workbook = workbook;
                    int x = workbook.NumberOfSheets; ;
                    List<string> sheetNames = new List<string>();
                    for (int i = 0; i < x; i++)
                    {
                        SheetNames.Add(workbook.GetSheetName(i));
                    }

                }
              
            }
            GetSheetNames = SheetNames;
            return GetSheetNames;
        }



        #endregion

    
        #region 获取数据源

        /// <summary>
        /// 获取所有数据,所有sheet的数据转化为datatable。
        /// </summary>
        /// <param name="isFirstRowCoumn">是否将第一行作为列标题</param>
        /// <returns></returns>
        public DataSet GetAllTables(bool isFirstRowCoumn)
        {
            var stopTime = new System.Diagnostics.Stopwatch();
            stopTime.Start();
            var ds = new DataSet();

            foreach (var sheetName in SheetNames)
            {
                ds.Tables.Add(ExcelToDataTable(sheetName, isFirstRowCoumn));
            }
            stopTime.Stop();
            Console.WriteLine("GetData:" + stopTime.ElapsedMilliseconds / 1000 + "S");
            return ds;
        }

        /// <summary>
        /// 获取第<paramref name="idx"/>的sheet的数据
        /// </summary>
        /// <param name="idx">Excel文件的第几个sheet表</param>
        /// <param name="isFirstRowCoumn">是否将第一行作为列标题</param>
        /// <returns></returns>
        public DataTable GetTable(int idx, bool isFirstRowCoumn)
        {
            if (idx >= SheetNames.Count || idx < 0)
                throw new Exception("Do not Get This Sheet");
            return ExcelToDataTable(SheetNames[idx], isFirstRowCoumn);
        }

        /// <summary>
        /// 获取sheet名称为<paramref name="sheetName"/>的数据
        /// </summary>
        /// <param name="sheetName">Sheet名称</param>
        /// <param name="isFirstRowColumn">是否将第一行作为列标题</param>
        /// <returns></returns>
        public DataTable GetTable(string sheetName, bool isFirstRowColumn)
        {
            return ExcelToDataTable(sheetName, isFirstRowColumn);
        }

        #endregion

        #region 方法

        /// <summary>
        /// 将excel中的数据导入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工作薄sheet的名称</param>
        /// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            var data = new DataTable();
            data.TableName = sheetName;
            int startRow = 0;
            try
            {
                sheet = sheetName != null ? _workbook.GetSheet(sheetName) : _workbook.GetSheetAt(0);
                if (sheet != null)
                {
                    var firstRow = sheet.GetRow(0);
                    if (firstRow == null)
                        return data;
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
                    startRow = isFirstRowColumn ? sheet.FirstRowNum + 1 : sheet.FirstRowNum;

                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        //.StringCellValue;
                        var column = new DataColumn(Convert.ToChar(((int)A) + i).ToString());
                        if (isFirstRowColumn)
                        {
                            var columnName = firstRow.GetCell(i).StringCellValue;
                            column = new DataColumn(columnName);
                        }
                        data.Columns.Add(column);
                    }


                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j, MissingCellPolicy.RETURN_NULL_AND_BLANK).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }
                else throw new Exception("Don not have This Sheet");

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        #endregion
    }
}

能读取.XLS 和.XLSX文件。

NPOI 辅助类

标签:

原文地址:http://www.cnblogs.com/liuruitao/p/4911132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!