1.NPOI读取Excel内容
private void button2_Click(object sender, EventArgs e)
{
//需要读取的文件:学生表.xls
// 创建文件
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Excel文件|*.xls";
ofd.ShowDialog();
string filePath = ofd.FileName;
FileStream fsRead=null;
IWorkbook wkBook = null;
if (filePath != "")
{
//1、创建一个工作簿workBook对象
fsRead = new FileStream(filePath, FileMode.Open);
//将学生表.xls中的内容读取到fsRead中
wkBook = new HSSFWorkbook(fsRead);
//2、遍历wkBook中的每个工作表Sheet
for (int i = 0; i < wkBook.NumberOfSheets; i++)
{
//获取每个工作表对象
ISheet sheet = wkBook.GetSheetAt(i);
//获取每个工作表的行
//foreach遍历 sheet.GetEnumerator
for (int r = 0; r < sheet.LastRowNum; r++)
{
//获取工作表中的每一行
IRow currentRow = sheet.GetRow(r);
//遍历当前行中的每个单元格
for (int c = 0; c < currentRow.LastCellNum; c++)
{
try
{
//获取每个单元格
ICell cell = currentRow.GetCell(c);
if (cell == null) //如果单元格为空时,程序会报错,这里判断提示用户,用try catch防止程序蹦
{
MessageBox.Show(string.Format("第{0}行,第{1}列单元格为空!",r,c));
}
CellType cType = cell.CellType; // 获取单元格中的类型
MessageBox.Show(cType.ToString());
//判断当前单元格的数据类型,可以拓展
switch (cType)
{
case CellType.Numeric: //数字
MessageBox.Show("我是数字");
break;
case CellType.String: //字符串
MessageBox.Show("我是字符串");