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;
}