C# NPOI 解析excel

首先貼整段代碼
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;


namespace NPOItest
{
    public partial class readExcel : System.Web.UI.Page
    {
        public void ExcelHelper(string fileName)
        {
            this.fileName = fileName;
            disposed = false;

        }

        protected void Page_Load(object sender, EventArgs e)
        {
           DataTable excelData =  ExcelToDataTable("列收信息", true);
           test1.DataSource = excelData;
           test1.DataBind();
           var a = 1;
        }

        //指定文件路徑
        private string fileName = "C:\\Users\\Administrator\\Desktop\\work\\成本\\列收模板.xlsx"; //文件名
        private IWorkbook workbook = null;  
        private FileStream fs = null;
        private bool disposed;


        /// <summary>
        /// 將DataTable數據導入到excel中
        /// </summary>
        /// <param name="data">要導入的數據</param>
        /// <param name="isColumnWritten">DataTable的列名是否要導入</param>
        /// <param name="sheetName">要導入的excel的sheet的名稱</param>
        /// <returns>導入數據行數(包含列名那一行)</returns>
        public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
        {
            int i = 0;
            int j = 0;
            int count = 0;
            ISheet sheet = null;

            fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                workbook = new XSSFWorkbook();
            else if (fileName.IndexOf(".xls") > 0) // 2003版本
                workbook = new HSSFWorkbook();

            try
            {
                if (workbook != null)
                {
                    sheet = workbook.CreateSheet(sheetName);
                }
                else
                {
                    return -1;
                }

                if (isColumnWritten == true) //寫入DataTable的列名
                {
                    IRow row = sheet.CreateRow(0);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                    }
                    count = 1;
                }
                else
                {
                    count = 0;
                }

                for (i = 0; i < data.Rows.Count; ++i)
                {
                    IRow row = sheet.CreateRow(count);
                    for (j = 0; j < data.Columns.Count; ++j)
                    {
                        row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                    }
                    ++count;
                }
                workbook.Write(fs); //寫入到excel
                return count;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 將excel中的數據導入到DataTable中
        /// </summary>
        /// <param name="sheetName">excel工做薄sheet的名稱</param>
        /// <param name="isFirstRowColumn">第一行是不是DataTable的列名</param>
        /// <returns>返回的DataTable</returns>
        public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                if (fileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (fileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                //獲取sheet
                if (sheetName != null)
                {
                    sheet = workbook.GetSheet(sheetName);
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }



                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最後一個cell的編號 即總的列數

                    if (isFirstRowColumn)
                    {
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            DataColumn column = new DataColumn(firstRow.GetCell(i).StringCellValue);
                            data.Columns.Add(column);
                        }
                        startRow = sheet.FirstRowNum + 1;
                    }
                    else
                    {
                        startRow = sheet.FirstRowNum;
                    }

                    //最後一列的標號
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //沒有數據的行默認是null       

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    if (fs != null)
                        fs.Close();
                }

                fs = null;
                disposed = true;
            }
        }




    }
}


上面的代碼包含一個寫excel的過程和一個解析excel的過程
讀取excel 使用NPOI庫 只須要4步
1.獲取excel文件資源
2.使用NPOI內的方法得到所要的sheet對象
3.獲取EXCEL內的一行
4.定位到這一行的某一列

首先是經過 FileStream得到這個文件的資源,而後經過獲取到的FS使用NPOI內的 XSSFXSSFWorkbook 和HSSFWorkbook 來得到一個excel對象 c#

fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);

在獲得整個EXCEL文件對象以後 調用GetSheet方法得到咱們須要解析的sheet sheet的話就是這個 標籤頁
經過這個標籤頁的名字來區別咱們要獲取這個文件內的那一張EXCEL表 this


//獲取sheet
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
}
else
{
sheet = workbook.GetSheetAt(0);
}
其中的sheetName就是 「列收信息」 到這裏咱們就取出了一張excel表 而後得事情就簡單了 sheet.GetRow(x).GetCell(y).ToString(); 得到X行Y列 不過記得是從0開始記數的,而後遍歷的話 要獲取長度  就是 sheet.LastRowNum 和 sheet.GetRow(0).LastCellNum 前一個是行數 後一個是列數  以後就是循環遍歷等亂七八糟的愛咋用咋用 基礎的東西大概就是這樣了
相關文章
相關標籤/搜索