C# Excel.Range.Text值即使在对列执行AutoFit()后仍读取为“”

C# Excel.Range.Text值即使在对列执行AutoFit()后仍读取为“”,c#,excel,vsto,C#,Excel,Vsto,我需要在一些excel数据的格式化值中读取日期、数字和文本的混合物,在运行之前,我不知道这些数据的格式为一系列行,丢弃所有空白单元格 我对输入列进行了自动拟合,因此理论上,这些列现在足够宽,这些单元格的显示值不应如此,但自动拟合似乎对我的输出数据没有影响 int rowCount = allCells.Rows.Count; int colCount = allCells.Columns.Count; List<List<string>> nonBlankValues =

我需要在一些excel数据的格式化值中读取日期、数字和文本的混合物,在运行之前,我不知道这些数据的格式为一系列行,丢弃所有空白单元格

我对输入列进行了自动拟合,因此理论上,这些列现在足够宽,这些单元格的显示值不应如此,但自动拟合似乎对我的输出数据没有影响

int rowCount = allCells.Rows.Count;
int colCount = allCells.Columns.Count;
List<List<string>> nonBlankValues = new List<List<string>>();


//to stop values coming out as series of #### due to column width, resize columns
foreach (Excel.Range col in allCells.Columns)
{
    col.AutoFit();
}
for (int i = 0; i < rowCount; i++)
{
    List<string> row = new List<string>();
    for (int j = 0; j < colCount; j++)
    {
        Excel.Range cellVal = (Excel.Range)allCells.Cells[i + 1, j + 1]; //Excel ranges are 1 indexed not 0 indexed
        string cellText = cellVal.Text.ToString();
        if (cellText != "")
        {
            row.Add(cellText);
        }

    }
    if (row.Count > 0)
    {
        nonBlankValues.Add(row);
    }
}

将格式设置为“常规”或类似的格式。不知道应用程序的确切代码,但应该是:

Range.NumberFormat = "General";
这对我来说很有效,我去掉了和一个单元格中最大字符数有关的字符。我用“标准”是因为我的版本是荷兰语。所以我想在英文版本中是“一般”的。就我而言,范围是:

Microsoft.Office.Interop.Excel.Range

手动调整列的大小似乎可以解决问题,因此

似乎我自己的AutoFit等价物是唯一的出路:所以我有两个选择

更快的方法是在读取数据之前向每一列添加一个固定的数量,然后在读取数据之后将其删除

    foreach (Excel.Range col in allCells.Columns)
    {
        col.ColumnWidth = (double)col.ColumnWidth + colWidthIncrease;
    }
…从这里的问题循环

    foreach (Excel.Range col in allCells.Columns)
    {
        col.ColumnWidth = (double)col.ColumnWidth - colWidthIncrease;
    }
B.有一个反馈循环,当我遇到一个仅为的条目时,迭代地增加一个固定的数量,直到循环计数器检查终止时该值发生变化

for (int i = 0; i < rowCount; i++)
{
    List<string> row = new List<string>();
    for (int j = 0; j < colCount; j++)
    {
        string cellText="";
        int maxLoops = 10;
        int loop = 0;
        bool successfulRead = false;
        while (!successfulRead && loop < maxLoops)
        {
            Excel.Range cellVal = (Excel.Range)allCells.Cells[i + 1, j + 1]; //Excel ranges are 1 indexed not 0 indexed
            cellText = cellVal.Text.ToString();
            if (!Regex.IsMatch(cellText, @"#+"))
            {
                successfulRead = true;
            }
            else
            {
                cellVal.EntireColumn.ColumnWidth = Math.Min((double)cellVal.EntireColumn.ColumnWidth + 5, 255);
            }
            loop++;
        }
        if (cellText != "")
        {
            row.Add(cellText);
        }

    }
    if (row.Count > 0)
    {
        nonBlankValues.Add(row);
    }
}

这与将Cell.Text替换为Cell.Value的操作相同,它让我解决了提取问题,但是它也覆盖了日期的格式设置,将日期设置回数值。我不能只使用datetime fromOA。。。转换方法,因为我不知道哪些列是在运行时更改的数据类型格式。