天天看點

C# NPOI導入Excel

NPOI是由國人開發的一個進行excel操作的第三方庫。其介紹如下:NPOI

本文主要介紹如何使用NPOI将Excel資料讀取。

首先引入程式集:

using System.IO;
using System.Reflection;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System.Web;
           

然後定位到檔案位置:

string path = "~/上傳檔案/custompersonsalary/" + id + "/"+id+".xls";
string filePath = Server.MapPath(path);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)  //打開.xls檔案
           

接下來,将xls檔案中的資料寫入workbook中:

wk.NumberOfSheets是xls檔案中總共的表的個數。

wk.GetSheetAt(i)是擷取第i個表的資料。

通過循環:

将每個表的資料單獨存放在ISheet對象中:

這樣某張表的資料就暫存在sheet對象中了。

接下來,我們可以通過sheet.LastRowNum來擷取行數,sheet.GetRow(j)來擷取第j行資料:

for (j = ; j <= sheet.LastRowNum; j++)  //LastRowNum 是目前表的總行數
   {
     IRow row = sheet.GetRow(j);  //讀取目前行資料
           

每一行的資料又存在IRow對象中。

我們可以通過row.LastCellNum來擷取列數,row.Cells[i]來擷取第i列資料。

row.Cells[].ToString();
           

這裡需要注意一點的就是,如果單元格中資料為公式計算而出的話,row.Cells[i]會傳回公式,需要改為:

就可以傳回計算結果了。

最後将我在項目中用到的一段導入Excel資料賦予實體的示例如下:

/// <summary>
        /// 導入操作
        /// </summary>
        ///  @author:  劉放
        ///  @date:    //
        /// <param name="id">主表id</param>
        /// <returns>如果成功,傳回ok,如果失敗,傳回不滿足格式的姓名</returns>   
        public string InDB(string id)
        {
            int j=;
            StringBuilder sbr = new StringBuilder();
            string path = "~/上傳檔案/custompersonsalary/" + id + "/"+id+".xls";
            string filePath = Server.MapPath(path);
            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))   //打開xls檔案
            {
                //定義一個工資詳細集合
                List<HR_StaffWage_Details> staffWageList = new List<HR_StaffWage_Details>();
                try
                {
                    HSSFWorkbook wk = new HSSFWorkbook(fs);   //把xls檔案中的資料寫入wk中
                    for (int i = ; i < wk.NumberOfSheets; i++)  //NumberOfSheets是xls檔案中總共的表數
                    {
                        ISheet sheet = wk.GetSheetAt(i);   //讀取目前表資料
                        for (j = ; j <= sheet.LastRowNum; j++)  //LastRowNum 是目前表的總行數
                        {
                            IRow row = sheet.GetRow(j);  //讀取目前行資料
                            if (row != null)
                            {
                                //for (int k = ; k <= row.LastCellNum; k++)  //LastCellNum 是目前行的總列數
                                //{
                                //如果某一行的員工姓名,部門,崗位和員工資訊表不對應,退出。
                                SysEntities db = new SysEntities();
                                if (CommonHelp.IsInHR_StaffInfo(db, row.Cells[].ToString(), row.Cells[].ToString(), row.Cells[].ToString()) == false)//姓名,部門,崗位
                                {
                                    //傳回名字以便提示
                                    return row.Cells[].ToString();
                                }
                                //如果符合要求,這将值放入集合中。
                                HR_StaffWage_Details hr_sw = new HR_StaffWage_Details();
                                hr_sw.Id = Result.GetNewIdForNum("HR_StaffWage_Details");//生成編号   
                                hr_sw.SW_D_Name = row.Cells[].ToString();//姓名
                                hr_sw.SW_D_Department = row.Cells[].ToString();//部門
                                hr_sw.SW_D_Position = row.Cells[].ToString();//職位
                                hr_sw.SW_D_ManHour = row.Cells[].ToString() != "" ? Convert.ToDouble(row.Cells[].ToString()) : ;//工數
                                hr_sw.SW_D_PostWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//基本工資
                                hr_sw.SW_D_RealPostWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//崗位工資
                                hr_sw.SW_D_PieceWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//計件工資
                                hr_sw.SW_D_OvertimePay = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//加班工資
                                hr_sw.SW_D_YearWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//年假工資
                                hr_sw.SW_D_MiddleShift = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//中班
                                hr_sw.SW_D_NightShift = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//夜班
                                hr_sw.SW_D_MedicalAid = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//醫補
                                hr_sw.SW_D_DustFee = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//防塵費
                                hr_sw.SW_D_Other = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//其他
                                hr_sw.SW_D_Allowance = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//津貼
                                hr_sw.SW_D_Heat = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//防暑費
                                hr_sw.SW_D_Wash = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//澡費
                                hr_sw.SW_D_Subsidy = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//補助
                                hr_sw.SW_D_Bonus = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//獎金
                                hr_sw.SW_D_Fine = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//罰款
                                hr_sw.SW_D_Insurance = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//養老保險
                                hr_sw.SW_D_MedicalInsurance = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//醫療保險
                                hr_sw.SW_D_Lunch = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//餐費
                                hr_sw.SW_D_DeLunch = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//扣餐費
                                hr_sw.SW_D_De = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//扣項
                                hr_sw.SW_D_Week = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//星期
                                hr_sw.SW_D_Duplex = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//雙工
                                hr_sw.SW_D_ShouldWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//應發金額
                                hr_sw.SW_D_IncomeTax = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//所得稅
                                hr_sw.SW_D_FinalWage = row.Cells[].NumericCellValue.ToString() != "" ? Convert.ToDouble(row.Cells[].NumericCellValue.ToString()) : ;//實發金額
                                hr_sw.SW_D_Remark = row.Cells[].ToString();//備注
                                hr_sw.SW_Id = id;//外鍵
                                hr_sw.SW_D_WageType = null;//工資類型

                                staffWageList.Add(hr_sw);
                            }
                        }
                    }
                }
                catch (Exception e) {
                    //錯誤定位
                    int k = j;
                }
                //再将list轉入資料庫
                double allFinalWage = ;
                foreach (HR_StaffWage_Details item in staffWageList)
                {
                    SysEntities db = new SysEntities();
                    db.AddToHR_StaffWage_Details(item);
                    db.SaveChanges();
                    allFinalWage +=Convert.ToDouble(item.SW_D_FinalWage);
                }
                //将總計賦予主表
                SysEntities dbt = new SysEntities();
                HR_StaffWage sw = CommonHelp.GetHR_StaffWageById(dbt, id);
                sw.SW_WageSum = Math.Round(allFinalWage,);
                dbt.SaveChanges();

            }
            sbr.ToString();
             return "OK";

        }
           

最後需要注意一點的就是,Excel中即使某些單元格内容為空,但是其依舊占據了一個位置,是以在操作的時候需要格外注意。

繼續閱讀