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

C#使用Office Interop读取Excel单元格数据丢失的解决方法

修复C# Interop Excel读取单元格末尾字符丢失问题

你的问题出在使用cell.Value?.ToString()读取单元格内容上——Value属性获取的是Excel单元格的内部存储值,如果单元格格式被Excel自动识别(比如误判内容格式),会导致文本被截断。要获取单元格显示的完整原始文本,应该改用Range.Text属性。

修改后的关键代码

将读取单元格内容的行:

string value = cell.Value?.ToString();

替换为:

string value = cell.Text;

完整修改后的代码

using System;
using System.Collections.Generic;
using Microsoft.Office.Interop.Excel;

namespace PracFileCreater
{
    class Program
    {
        static void Main(string[] args)
        {
            string filePath = "test.xlsx";

            int sheetNum = 1;
            string columnName = "E";
            int startRow = 6;
            int endRow = 39;

            Application app = new Application();
            List<string> pracNameList = ReadWorksheetColumn(app, filePath, sheetNum, columnName, startRow, endRow);
            foreach (string name in pracNameList)
            {
                Console.WriteLine(name);
            }
            app.Quit();
        }

        static List<string> ReadWorksheetColumn(Application app, string path, int sheetNum, string columnName, int startRow, int endRow)
        {
            List<string> pracNameList = new List<string>();

            Workbook workbook = app.Workbooks.Open(path);
            Worksheet worksheet = workbook.Sheets[sheetNum];
            Range pracNameRange = worksheet.Range[columnName + startRow.ToString() + ":" + columnName + endRow.ToString()];
            
            foreach (Range cell in pracNameRange.Cells)
            {
                string value = cell.Text;
                if (!string.IsNullOrEmpty(value))
                {
                    pracNameList.Add(value);
                }
            }

            workbook.Close(false);

            return pracNameList;
        }
    }
}

修改后执行代码,就能正确读取到"演習4-3f"和"演習4-3w",不会丢失末尾字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:19:59