Read data from Excel using NPOI in C#

Read a column from Excel sheet

Posted by Shengwen on February 18, 2017

In this example, we simply read a column from an Excel sheet and print each value in console.

NPOI is the C# implementation of Java POI. The index of row and column (cells in a row) starts from 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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);
    }
}