• 使用NPOI组件读取excel数据


    分享一段代码,将excel数据读取到DataTable:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Text;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    
    namespace ConsoleApp.Utility
    {
        public class ExcelBuilder
        {
            /// <summary>
            /// exact excel data into DataTable
            /// </summary>
            /// <param name="excel">excel file name</param>
            /// <param name="index">sheet index </param>
            /// <param name="header"> the first row in excel whether belongs the columns</param>
            /// <returns>DataTable</returns>
            public static DataTable ToDataTable(string excel,int index, bool header)
            {
                DataTable dt = new DataTable(Path.GetFileNameWithoutExtension(excel) + "_Sheet" + index);
                IWorkbook workbook;
                using (FileStream file = new FileStream(excel, FileMode.Open, FileAccess.Read))
                {
                    workbook = new XSSFWorkbook(file);
                }
                ISheet sheet = workbook.GetSheetAt(index);
                var rows = sheet.GetRowEnumerator();
    
                rows.MoveNext();
                IRow row = (XSSFRow)rows.Current;
                
                for (int i = 0; i < row.LastCellNum; i++)
                {
                    ICell cell = row.GetCell(i);
                    string columnName = header ? cell.StringCellValue : i.ToString();
                    dt.Columns.Add(columnName, typeof(string));
                }
                if (!header)
                {
                    DataRow first = dt.NewRow();
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        first[i] = cell.StringCellValue;
                    }
                    dt.Rows.Add(first);
                }
               
                while (rows.MoveNext())
                {
                    row = (XSSFRow)rows.Current;
                    DataRow dataRow = dt.NewRow();
                   
                    for (int i = 0; i < row.LastCellNum; i++)
                    {
                        ICell cell = row.GetCell(i);
                        dataRow[i] = cell.StringCellValue;
                    }
                    dt.Rows.Add(dataRow);
                }
                
                return dt;
            }
        }
    }
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    经典机器学习算法总结
    从0开始学Python---01
    Android-Canvas.save() Canvas.restore() 总结
    Android-属性动画原理总结
    设计模式-外观模式
    设计模式-模板方法
    设计模式-装饰者模式
    设计模式-策略模式
    设计模式-工厂方法模式
    设计模式-简单工厂模式
  • 原文地址:https://www.cnblogs.com/ecin/p/2828013.html
Copyright © 2020-2023  润新知