1

我需要读取一些 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);
    }
}
4

2 回答 2

0

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

Range.NumberFormat = "General";

这对我有用,我摆脱了###(与单元格中的最大字符数有关)。(我使用“标准”,因为我的版本是荷兰语)。所以我想它是英文版本中的“General”。范围在我的情况下:

Microsoft.Office.Interop.Excel.Range
于 2013-06-19T07:57:24.117 回答
0

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

似乎让我自己的 AutoFit 等效是唯一的方法:(所以我有两个选择......

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

    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);
    }
}
于 2013-06-20T05:36:09.197 回答