c#读excel 不用office组件

某日笔者写了个导入导出excel的小程序,拿给别人用时,别人说程序有问题读不了。

究其原因发现原来是using Microsoft.Office.Interop.Excel;引用出错。发现他装的office是精简版。

在网上查资料时发现了一遍文章 4种开源Excel读写类库与MS Excel类库写操作对比  里面分析了4中开源的读写excel的类库。分析了这篇文章的数据后。选择了NPOI。

什么是NPOI?

曰:是POI的.NET版本。那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等。

下载地址  


下载下来后,发现有很多demo,又懒得看,找到dll类库,又在网上找了片言只语。发现有的代码可以,有的代码不可以。究其原因是npoi处理excel时分xls和xlsx之分。所以闲着没事,自己就封装了一个读excel的类

 代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Collections;

namespace WindowsFormsApplication1
{
    /// <summary>
    /// Excel的辅助类
    /// </summary>
    public class ExcelHelper
    {
        /// <summary>
        /// 读取excel到datatable中
        /// </summary>
        /// <param name="excelPath">excel地址</param>
        /// <param name="sheetIndex">sheet索引</param>
        /// <returns>成功返回datatable,失败返回null</returns>
        public static DataTable ImportExcel(string excelPath, int sheetIndex)
        {
            
            IWorkbook workbook = null;//全局workbook
            ISheet sheet;//sheet
            DataTable table = null;
            try
            {
                FileInfo fileInfo = new FileInfo(excelPath);//判断文件是否存在
                if (fileInfo.Exists)
                {
                    FileStream fileStream = fileInfo.OpenRead();//打开文件,得到文件流
                    switch (fileInfo.Extension)
                    {
                        //xls是03,用HSSFWorkbook打开,.xlsx是07或者10用XSSFWorkbook打开
                        case ".xls": workbook = new HSSFWorkbook(fileStream); break;
                        case ".xlsx": workbook = new XSSFWorkbook(fileStream); break;
                        default: break;
                    }
                    fileStream.Close();//关闭文件流
                }
                if (workbook != null)
                {
                    sheet = workbook.GetSheetAt(sheetIndex);//读取到指定的sheet
                    table = new DataTable();//初始化一个table

                    IRow headerRow = sheet.GetRow(0);//获取第一行,一般为表头
                    int cellCount = headerRow.LastCellNum;//得到列数

                    for (int i = headerRow.FirstCellNum; i < cellCount; i++)
                    {
                        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);//初始化table的列
                        table.Columns.Add(column);
                    }
                    //遍历读取cell
                    for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
                    {
                        NPOI.SS.UserModel.IRow row = sheet.GetRow(i);//得到一行
                        DataRow dataRow = table.NewRow();//新建一个行

                        for (int j = row.FirstCellNum; j < cellCount; j++)
                        {
                            ICell cell = row.GetCell(j);//得到cell
                            if (cell == null)//如果cell为null,则赋值为空
                            {
                                dataRow[j] = "";
                            }
                            else
                            {
                                dataRow[j] = row.GetCell(j).ToString();//否则赋值
                            }
                        }

                        table.Rows.Add(dataRow);//把行 加入到table中

                    }
                }
                return table;

            }
            catch (Exception e)
            {
                return table;
            }
            finally
            {
                //释放资源
                if (table != null) { table.Dispose(); }
                workbook = null;
                sheet = null;
            }
        }

    }
}

关于写excel 请参考笔者的上一篇文章 http://www.cnblogs.com/Bonker/p/3246369.html

原文地址:https://www.cnblogs.com/Bonker/p/3253199.html