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

如何用C#解决SAP导出Excel列文本转数字后求和问题

解决方案

问题根源是SAP导出的Excel中,目标列的数字以文本格式存储(可能带前置撇号或格式设为文本),直接用GetValue<double>()无法正确解析,导致求和失败。以下是修改后的代码及关键处理步骤:

关键修改点

  1. 先读取单元格的文本值,去除可能的前置撇号和空白字符
  2. 使用double.TryParse安全转换为数值,避免转换失败抛出异常
  3. 可选:将单元格格式改为数字格式并重新赋值,确保Excel后续能正常识别为数字

修改后的完整代码

private void CalculateAndWriteSum(IXLWorksheet worksheet, int startRow)
{
    int previousRowIndex = 0;

    foreach (var dataRow in worksheet.Rows(startRow, worksheet.LastRowUsed().RowNumber()))
    {
        int currentRowIndex = dataRow.RowNumber();

        if (currentRowIndex - previousRowIndex > 1)
        {
            double sum = 0;

            for (int rowIndex = previousRowIndex + 1; rowIndex < currentRowIndex; rowIndex++)
            {
                // 读取文本值并清理前置撇号和空白
                string cellText = worksheet.Cell(rowIndex, 11).GetValue<string>().TrimStart('\'').Trim();
                
                // 安全转换为double,转换成功才累加
                if (double.TryParse(cellText, out double value))
                {
                    sum += value;
                    
                    // 可选:将单元格改为数字格式并赋值,让Excel界面识别为数字
                    worksheet.Cell(rowIndex, 11).Style.Numberformat.Format = "0.00";
                    worksheet.Cell(rowIndex, 11).Value = value;
                }
                // 可根据需求添加转换失败的处理逻辑,比如记录日志或设为0
            }

            worksheet.Cell(previousRowIndex + 1, 11).Value = sum;
            // 同样设置求和结果的单元格格式为数字
            worksheet.Cell(previousRowIndex + 1, 11).Style.Numberformat.Format = "0.00";
        }

        previousRowIndex = currentRowIndex;
    }

    // Calculate and insert sum in the last row
    int lastRowIndex = worksheet.LastRowUsed().RowNumber();

    if (lastRowIndex - previousRowIndex > 0)
    {
        double sum = 0;

        for (int rowIndex = previousRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++)
        {
            string cellText = worksheet.Cell(rowIndex, 11).GetValue<string>().TrimStart('\'').Trim();
            
            if (double.TryParse(cellText, out double value))
            {
                sum += value;
                
                worksheet.Cell(rowIndex, 11).Style.Numberformat.Format = "0.00";
                worksheet.Cell(rowIndex, 11).Value = value;
            }
        }

        worksheet.Cell(lastRowIndex + 1, 11).Value = sum;
        worksheet.Cell(lastRowIndex + 1, 11).Style.Numberformat.Format = "0.00";
    }
}

补充说明

  • 如果SAP导出的数字包含千分位分隔符或特殊小数点(如逗号),可以在TryParse中指定文化信息,例如:
    if (double.TryParse(cellText, NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out double value))
    
  • 若不需要修改原单元格格式,仅需求和,可以去掉设置Style.Numberformat.Format和重新赋值的代码,只保留转换累加逻辑即可。

内容的提问来源于stack exchange,提问作者k.sere

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 20:59:53