甚至在执行AutoFit()on列后,Excel.Range.Text值仍然以“######”的forms读取

我需要读取一些excel数据的格式化值(date,数字和文本的混合,我不知道运行之前的格式)作为一系列行,丢弃所有空白单元格。

我在input列上做了一个自动调整,所以理论上现在列已经足够宽了,这些单元的显示值不应该是####,但是自动调整似乎对我的输出数据没有影响。

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"; 

这工作对我来说,我摆脱了###(与单元格的最大数量的字符有关)。 (我使用了“Standaard”,因为我的版本是荷兰语)。 所以我想这是英文版的“一般”。 范围是在我的情况:

 Microsoft.Office.Interop.Excel.Range 

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

似乎使我自己的AutoFit相当于唯一的方法去:(所以我有2个选项…

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

  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); } }