读取Execl

public class readExecl

{

private string FilePath;

private ICell cell;

public readExecl(string FilePath)

{

this.FilePath = FilePath;

// this.cell = cell;

}

public void ReadFromExcelFile()

{

IWorkbook wk = null;

string extension = System.IO.Path.GetExtension(this.FilePath);

try

{

FileStream fs = File.OpenRead(this.FilePath);

if (extension.Equals(".xls"))

{

//把xls文件中的数据写入wk中

wk = new HSSFWorkbook(fs);

}

else

{

//把xlsx文件中的数据写入wk中

wk = new XSSFWorkbook(fs);

}

fs.Close();

//读取当前表数据

ISheet sheet = wk.GetSheetAt(0);

IRow row = sheet.GetRow(0); //读取当前行数据

DataTable dt = new DataTable();

//LastRowNum 是当前表的总行数-1(注意)

int offset = 0;

for (int i = 0; i <= sheet.LastRowNum; i++)

{

row = sheet.GetRow(i); //读取当前行数据

if (row != null)

{

//LastCellNum 是当前行的总列数

for (int j = 0; j < row.LastCellNum; j++)

{

//读取该行的第j列数据

string value = row.GetCell(j).ToString();

Console.Write(value.ToString() + " ");

}

Console.WriteLine("\n");

}

}

}

catch (Exception e)

{

//只在Debug模式下才输出

Console.WriteLine(e.Message);

}

}

//获取cell的数据,并设置为对应的数据类型

public object GetCellValue(ICell cell)

{

object value = null;

try

{

if (cell.CellType != CellType.Blank)

{

switch (cell.CellType)

{

case CellType.Numeric:

// Date comes here

if (DateUtil.IsCellDateFormatted(cell))

{

value = cell.DateCellValue;

}

else

{

// Numeric type

value = cell.NumericCellValue;

}

break;

case CellType.Boolean:

// Boolean type

value = cell.BooleanCellValue;

break;

case CellType.Formula:

value = cell.CellFormula;

break;

default:

// String type

value = cell.StringCellValue;

break;

}

}

}

catch (Exception)

{

value = "";

}

return value;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值