1. 程式人生 > >C#利用NPOI逐列讀取excel內容

C#利用NPOI逐列讀取excel內容

C# NPOI 讀取excel

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
{
///
/// 逐列讀取excel內容,如果某個單元格中無內容,則將以空字符串形式填寫到List《string》的相應位置,以string.IsNullOrEmpty(str)形式判斷是否為空即可

///
/// 代表excel表格保存的地址,包括"文件名.xls"
/// 代表數據讀取的起始行(1,2,3.......65536)最多支持65536行
/// 代表數據讀取的結束行(1,2,3.......65536)最多支持65536行
/// 代表數據讀取的起始列(1,2,3......256)最多支持256列
/// 代表數據讀取的結束列(1,2,3......256)最多支持256列
/// 代表將要讀取的sheet表的索引位置
/// 返回 “不為空” 代表讀取成功,否則為讀取失敗;讀取數據list《string》代表一列數據,有多少個就代表有多列數據(所有列上對齊)

public static List> colReadSection(string save_address, int start_row, int stop_row,
int sart_column, int stop_column, int sheet_number)//讀取excel表格相應工作表的部分數據
{
List> data = null;//初始化為空
FileStream readfile = null;

try
{

//如果傳入參數合法
if (!string.IsNullOrEmpty(save_address) && start_row > 0 && stop_row > 0 && sart_column > 0 && stop_column > 0 && 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)
{
for (int columnIndex = sart_column - 1; columnIndex < stop_column; columnIndex++) {
List oneCol= new List();

for (int rowIndex = start_row - 1; rowIndex < stop_row; rowIndex++) {
IRow row = sheet.GetRow(rowIndex);
if (row != null)
{
ICell cell = row.GetCell(columnIndex);
if (cell != null)
{
oneCol.Add(cell.StringCellValue);
}
else
{
oneCol.Add("");//填充空的數據
}
}
else {
oneCol.Add("");//填充空的數據
}
}

if (data == null)
{
data = new List>();//初始化
}
data.Add(oneCol);
}
}
}
}
catch (Exception)
{
Console.WriteLine("NpoiOperateExcel.colReadSection方法產生了異常!");
}
finally
{
if (readfile != null) { readfile.Close(); }
}


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

C#利用NPOI逐列讀取excel內容