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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM