C#讀取excel的有效行數或者最大有效列數

內容所有權屬於:http://www.xinduofen.cn/

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using NPOI.SS.UserModel;

using NPOI.HSSF.UserModel;

using System.IO;


namespace www.xinduofen.cn

{

    class NpoiOperateExcel

    {

        

/// <summary>

        /// 讀取某一個excel文件的某一個工作表的有效行數或者最大有效列數

        /// </summary>

        /// <param name="save_address">代表excel表格保存的地址,包括"文件名.xls"</param>

        /// <param name="sheet_number">代表將要讀取的sheet表的索引位置</param>

        /// <param name="readFlag">爲true代表讀取的爲:有效行數,爲:false代表讀取的爲:最大有效列數</param>

        /// <returns>返回值 “不爲-1” 代表讀取成功,否則爲讀取失敗</returns>

        public static int rowORcolAllCount(string save_address, int sheet_number, Boolean readFlag)//讀取excel表格相應工作表的所有數據

        {

            int rowORcolCnt = -1;//初始化爲-1

            FileStream readfile = null;


            try

            {

                //如果傳入參數合法

                if (!string.IsNullOrEmpty(save_address) && sheet_number > 0)

                {

                    readfile = new FileStream(save_address, FileMode.Open, FileAccess.Read);

                    HSSFWorkbook hssfworkbook = new HSSFWorkbook(readfile);

                    ISheet sheet = hssfworkbook.GetSheetAt(sheet_number - 1);

                    if (sheet != null)

                    {

                        if (readFlag)//如果需要讀取‘有效行數’

                        {

                            rowORcolCnt = sheet.LastRowNum+1;//有效行數(NPOI讀取的有效行數不包括列頭,所以需要加1)

                        }

                        else

                        { //如果需要讀取‘最大有效列數’

                            for (int rowCnt = sheet.FirstRowNum; rowCnt <= sheet.LastRowNum; rowCnt++)//迭代所有行

                            {

                                IRow row = sheet.GetRow(rowCnt);

                                if (row != null && row.LastCellNum > rowORcolCnt)

                                {

                                    rowORcolCnt = row.LastCellNum;

                                }

                            } 

                        }

                    }

                }

            }

            catch (Exception)

            {

                Console.WriteLine("NpoiOperateExcel.rowOrColumnAllCount方法產生了異常!");

            }

            finally

            {

                if (readfile != null) { readfile.Close(); }

            }



            return rowORcolCnt;

        }

    }

}

內容所有權屬於:北京繼豪電子(專業研究體質測試儀器)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章