You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用IronXL导入Excel到C#字典时int.Parse报错,脚本无法运行

排查IronXL导入Excel时int.Parse失败的问题

常见原因及解决步骤

1. Excel第二列存在非有效整数值

检查Excel文件第二列内容:是否包含空格、字母、小数点、千分分隔符(如1,234),或是空值、带不可见字符(换行符、制表符)的文本格式数字。

  • 解决:清理Excel数据确保第二列均为纯整数;或在代码中先清理字符串:
    var valueStr = row.Columns[1].Value?.ToString().Trim() ?? string.Empty;
    

2. 循环包含表头行

若Excel第一行是表头(如"Key"、"Value"),循环会将表头文本传入int.Parse,直接触发转换失败。

  • 解决:跳过表头行,从第二行开始遍历:
    foreach (var row in workSheet.Rows.Skip(1))
    

3. IronXL单元格Value的类型问题

IronXL的Value属性可能返回DBNull、double(Excel默认数字类型),直接ToString()可能出现123.0这类格式问题,导致转换失败。

  • 解决:直接判断Value类型或使用IronXL自带转换逻辑:
    if (row.Columns[1].Value is int intValue)
    {
        dataDictionary.Add(key, intValue);
    }
    else if (row.Columns[1].Value is double doubleValue && doubleValue % 1 == 0)
    {
        dataDictionary.Add(key, (int)doubleValue);
    }
    

4. 未处理转换异常

即使做了前置检查,仍可能存在意外数据,直接用int.Parse会抛出FormatException或OverflowException。

  • 解决:改用int.TryParse安全转换,避免程序崩溃:
    if (!string.IsNullOrEmpty(key) && int.TryParse(valueStr, out int intValue))
    {
        dataDictionary.Add(key, intValue);
    }
    // 可选:记录转换失败的行,方便排查问题
    else if (!string.IsNullOrEmpty(key))
    {
        // 示例:Console.WriteLine($"无法转换值 '{valueStr}' 为整数,对应键:{key}");
    }
    

优化后的完整代码

using System.IO;
using IronXL;
using System.Collections.Generic;
using System.Linq;

public Dictionary<string, int> ReadInputData_3()
{
    Dictionary<string, int> dataDictionary = new Dictionary<string, int>();
    string filePath = "../../../ModbusTestJig.Helpers/Input_data/Input_data.xlsx";
    
    // 先检查文件是否存在,避免未找到文件异常
    if (!File.Exists(filePath))
    {
        throw new FileNotFoundException("目标Excel文件不存在", filePath);
    }

    WorkBook workBook = WorkBook.Load(filePath);
    WorkSheet workSheet = workBook.WorkSheets[0];

    // 跳过表头行,从第二行开始读取数据
    foreach (var row in workSheet.Rows.Skip(1))
    {
        var key = row.Columns[0].Value?.ToString().Trim() ?? string.Empty;
        var valueStr = row.Columns[1].Value?.ToString().Trim() ?? string.Empty;

        if (!string.IsNullOrEmpty(key) && int.TryParse(valueStr, out int intValue))
        {
            // 处理重复键:按需选择添加或覆盖
            if (!dataDictionary.ContainsKey(key))
            {
                dataDictionary.Add(key, intValue);
            }
            else
            {
                // dataDictionary[key] = intValue;  // 若需要覆盖重复键值,取消注释
            }
        }
    }

    return dataDictionary;
}

内容的提问来源于stack exchange,提问作者coderatnam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 21:54:58