首页 > 解决方案 > c#中如何使用NPOI库选择数据

问题描述

我有一个三列(姓名、性别、电子邮件、工资)的 excel 表,我想使用 NOPI 库编写一个控制台应用程序来选择所有工资最高的男性数据

我使用此代码从 xl 读取文件

using System;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

private static void procExcel(string fileName, string schoolPicDir){
    try
    {
        IWorkbook workbook;
        FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
        if (fileName.IndexOf(".xlsx") > 0) 
            workbook = new XSSFWorkbook(fs);
        else if (fileName.IndexOf(".xls") > 0) 
            workbook = new HSSFWorkbook(fs);
        //First sheet
        ISheet sheet = workbook.GetSheetAt(0);
        if (sheet != null)
        { 
            int rowCount = sheet.LastRowNum; // This may not be valid row count.
            // If first row is table head, i starts from 1
            for (int i = 1; i <= rowCount; i++)
            {
                IRow curRow = sheet.GetRow(i);
                // Works for consecutive data. Use continue otherwise 
                if (curRow == null)
                {
                    // Valid row count
                    rowCount = i - 1;
                    break;
                }
                // Get data from the 4th column (4th cell of each row)
                var cellValue = curRow.GetCell(3).StringCellValue.Trim();
                Console.WriteLine(cellValue);
            }
        }
    }
    catch(Exception e)
    {
        Console.WriteLine(e.Message);
    }
}

标签: c#npoi

解决方案


推荐阅读