1. 程式人生 > 實用技巧 >C# NPOI 讀取Excel資料,附案例原始碼

C# NPOI 讀取Excel資料,附案例原始碼

專案結構

注意:需要引入NPOI類庫

C#程式碼

Form1.cs

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NPOIDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private const int DEFAULT_CHECK_CELL_NUM = 4; private void button1_Click(object sender, EventArgs e) { try { DataTable dt
=ReadExcelData(@"C:\Users\apple\Desktop\Test.xls"); MessageBox.Show("ok"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// 讀取Excel中資料 /// </summary>
/// <param name="filePath"></param> private DataTable ReadExcelData(object filePath) { try { if (!File.Exists(filePath.ToString())) { throw new Exception("檔案不存在!"); } DataTable dtExcel = InitDataTable(); FileStream fsRead = new FileStream(filePath.ToString(), FileMode.Open); //建立工作薄 IWorkbook workBook = new HSSFWorkbook(fsRead); //獲取Sheet ISheet sheet = workBook.GetSheetAt(0); //獲取Excel中的行數 int ExcelRowsCount = sheet.LastRowNum; Assert.IsTrue(ExcelRowsCount == 1, "未讀到Excel資料!"); IRow currentRow; DataRow dr; for (int i = 1; i < ExcelRowsCount; i++) { dr = dtExcel.NewRow(); //當前行資料 currentRow = sheet.GetRow(i); SetCurrentRowValue(dtExcel, dr, currentRow, currentRow.LastCellNum); } return dtExcel; } catch (Exception ex) { throw ex; } } /// <summary> /// 初始化DataTable /// </summary> /// <returns></returns> private DataTable InitDataTable() { DataTable dt_excel = new DataTable(); dt_excel.Columns.Add("A"); dt_excel.Columns.Add("B"); dt_excel.Columns.Add("C"); dt_excel.Columns.Add("D"); return dt_excel; } /// <summary> /// 讀取到的Excel的單元格數量 /// </summary> /// <param name="currentCellNum"></param> private void CheckExcelCellNum(int readCurrentRowCellNum) { Assert.IsTrue(readCurrentRowCellNum > DEFAULT_CHECK_CELL_NUM, "Excel單元格列數超過:"+DEFAULT_CHECK_CELL_NUM+""); } /// <summary> /// 給DataTable動態賦值 /// </summary> /// <param name="dr">DataTable當前行</param> /// <param name="currentRow">Excel當前行資料</param> /// <param name="currentCellNum">Excel的列數</param> private void SetCurrentRowValue(DataTable dtExcel, DataRow dr,IRow currentRow, int currentCellNum) { dr.BeginEdit(); for (int j = 0; j < currentCellNum; j++) { if (j >= DEFAULT_CHECK_CELL_NUM) break; dr[j]= currentRow.GetCell(j).ToString().Trim(); } dr.EndEdit(); dtExcel.Rows.Add(dr); } } }

Assert.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NPOIDemo
{
    public static class Assert
    {
        public static void IsTrue(bool flag,string msg)
        {
            if (flag)
            {
                throw new Exception(msg);
            }
        }
    }
}

演示

  演示過程中,提示另外一個程序xxxx的,是因為NPOI讀取Excel的時候,Excel不可以開啟,我們關閉,然後再次執行即可

專案下載

連結:https://pan.baidu.com/s/1YLer2fgV6QhJIQVsxqozJQ 
提取碼:30a9