NPOI.HSSF 导入excel数据(记录)

https://download.csdn.net/download/ttbat/15435334  NPOI.HSSF.Dll 下载地址。

在项目引用 NPOI.HSSF.Dll 后 using NPOI.HSSF.UserModel;

PS:excel文件只能读取1997-2003版本的,2007以上的excel版本无法读取。

        /// <summary>
        /// 
        /// </summary>
        /// <param name="path">文件地址</param>
        /// <param name="_syptktService"></param>
        /// <param name="success">成功数量</param>
        /// <param name="failure">错误数量</param>
        /// <returns></returns>
public static string ImprotSXSC(string path, ISYPTKTService _syptktService, out int success, out int failure)
        {
            string errorMsg = string.Empty;
            success = failure = 0;
            try
            {
                HSSFWorkbook hssfworkbook;
                using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    #region 检查excel数据
                    hssfworkbook = new HSSFWorkbook(file);
                    HSSFSheet sheet = hssfworkbook.GetSheetAt(0);
                    if (sheet == null || sheet.LastRowNum < 0)
                    {
                        errorMsg = "excel格式异常,请检查";
                        return errorMsg;
                    }
                    Dictionary<string, int> headCellDic = GetCellDictNum(sheet, 0); //表头键与索引集合
                    errorMsg = CheckExcel(sheet);
                    if (!string.IsNullOrEmpty(errorMsg))
                        return errorMsg;
                    #endregion
                    HSSFRow row = null;
                    HSSFCell cell;
                    string rowMsg;
                    int startRowIndex = 1;
                    for (int i = startRowIndex; i <= sheet.LastRowNum; i++)
                    {                        
                        row = sheet.GetRow(i);
                        cell = row.GetCell(headCellDic["A"]);
                        string name = getCellStringValue(row, cell, "A", out rowMsg);
                        var model = _syptktService.GetSxScxts(s => s.NAME.Contains(name)).FirstOrDefault();
                        bool isnew = false;int failure1 = 0;
                        if (model == null)
                        {
                            model = new SXSCXTEntiry();
                            isnew = true;
                        }
                        model.NAME = name;
                        cell = row.GetCell(headCellDic["B"]);
                        string X = getCellStringValue(row, cell, "B", out rowMsg);
                        cell = row.GetCell(headCellDic["C"]);
                        string Y = getCellStringValue(row, cell, "C", out rowMsg);
                        float x = CommonMethodNew.FromDFM(X);
                        float y = CommonMethodNew.FromDFM(Y);
                        model.X = X;
                        model.Y = Y;
                        if (X != "" && Y != "" && x >= 3 && y >= 2)
                        {
                            model.SHAPE = "POINT ( " + x + " " + y + ")";
                        }
                        if (string.IsNullOrEmpty(name))
                        {
                            failure1++;
                             errorMsg += string.Format("第{0}行水下生产系统名称未录入$", i);
                        }
                        if (string.IsNullOrEmpty(model.SHAPE))
                        {
                            failure1++;
                            errorMsg += string.Format("{0}水下生产系统经纬度数据不正确$", name);                           
                        }
                        if (failure1 > 0)
                        { failure++; continue; }
                    }
                }
            }
            catch (Exception ex)
            {
                failure++;
                errorMsg = ex.ToString();
            }
            return errorMsg;
        }
        /// <summary>
        /// 获取excel指定行中,列键值(键/索引)集合
        /// </summary>
        /// <param name="sheet"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static Dictionary<string, int> GetCellDictNum(HSSFSheet sheet,int rowIndex)
        {

            Dictionary<string, int> celldict = new Dictionary<string, int>();
            HSSFRow frow = sheet.GetRow(rowIndex);
            int colNum = frow.PhysicalNumberOfCells;
            char A = 'A';
            int Acode = (int)A;

            int firA = 0;
            String sfir = "";
            String stow = "";

            for (int i = 0; i < colNum; i++)
            {
                if (i < 26)
                {
                    celldict.Add(((char)(Acode + i)).ToString(), i);
                }
                else if (i >= 26 && i <= (26 * 26))
                {
                    firA = i / 26;
                    sfir = ((char)(Acode + firA - 1)).ToString();
                    firA = i % 26;
                    stow = ((char)(Acode + firA)).ToString();
                    celldict.Add(sfir + stow, i);
                }
            }
            return celldict;
        }
        /// <summary>
        /// 获取文本格式
        /// </summary>
        /// <param name="row"></param>
        /// <param name="cell"></param>
        /// <param name="cellKey"></param>
        /// <param name="errorMsg"></param>
        /// <returns></returns>
        public static string getCellStringValue(HSSFRow row, HSSFCell cell, string cellKey, out string errorMsg)
        {
            errorMsg = string.Empty;
            string value = null;
            if (cell == null)
            {
                return null;
            }
            if (cell.CellType == HSSFCell.CELL_TYPE_NUMERIC)
                value= cell.NumericCellValue.ToString();
            else if (cell.CellType == HSSFCell.CELL_TYPE_STRING)
                value= cell.StringCellValue;
            else
            {
                try
                {
                    value = cell.StringCellValue;
                }
                catch (Exception ex)
                {
                    errorMsg = string.Format("文档第" + (row.RowNum + 1) + "行," + cellKey + "列格式不正确");
                }
            }
            if(!string.IsNullOrEmpty(value))value = value.Trim().Replace("\n", "").Replace(" ", "").Replace("\t", "").Replace("\r", ""); ;
            return value;
        }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
使用NPOI导入Excel文件可以使用以下步骤: 1. 添加NPOI引用:在Visual Studio中,右键单击项目,选择“管理NuGet程序包”,搜索NPOI并安装。 2. 导入命名空间:在代码文件中添加以下命名空间引用: ``` using NPOI.HSSF.UserModel; // for *.xls files using NPOI.XSSF.UserModel; // for *.xlsx files using NPOI.SS.UserModel; // for both *.xls and *.xlsx files ``` 3. 加载Excel文件:使用以下代码打开Excel文件: ``` string filePath = @"C:\Sample.xlsx"; // file path of the Excel file IWorkbook workbook; // initialize the workbook variable using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (Path.GetExtension(filePath) == ".xls") { workbook = new HSSFWorkbook(fileStream); // for *.xls files } else { workbook = new XSSFWorkbook(fileStream); // for *.xlsx files } } ``` 4. 读取工作表和行:使用以下代码读取工作表和行: ``` ISheet sheet = workbook.GetSheetAt(0); // get the first worksheet IRow row = sheet.GetRow(0); // get the first row ``` 5. 读取单元格值:使用以下代码读取单元格值: ``` string cellValue = row.GetCell(0).ToString(); // get the value of the first cell in the first row ``` 6. 循环读取单元格值:使用以下代码循环读取单元格值: ``` for (int i = 0; i < sheet.LastRowNum; i++) { row = sheet.GetRow(i); // get the i-th row if (row != null) { for (int j = 0; j < row.LastCellNum; j++) { string cellValue = row.GetCell(j).ToString(); // get the value of the j-th cell in the i-th row // do something with the cell value } } } ``` 以上是使用NPOI导入Excel文件的基本步骤。需要注意的是,NPOI只支持读取Excel文件,如果需要写入Excel文件,需要使用另外的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值