Excel使用C#Microsoft Interop Excel在第144行后返回Null
在C#中,我打开了一个Excel电子表格,并对其进行迭代。无论何时到达第144行,电子表格值都会为其后的每一行返回null。查看电子表格,第144-250行显然不是空的。我试着将它保存在不同的版本中,但没有成功。我试着复制并粘贴到一个全新的工作表中。什么都没起作用。这是我的密码:Excel使用C#Microsoft Interop Excel在第144行后返回Null,c#,excel,excel-interop,C#,Excel,Excel Interop,在C#中,我打开了一个Excel电子表格,并对其进行迭代。无论何时到达第144行,电子表格值都会为其后的每一行返回null。查看电子表格,第144-250行显然不是空的。我试着将它保存在不同的版本中,但没有成功。我试着复制并粘贴到一个全新的工作表中。什么都没起作用。这是我的密码: // initiate Excel Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.W
// initiate Excel
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(lblFileName.Text, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
//Get the used Range
Excel.Range usedRange = xlWorkSheet.UsedRange;
//Iterate the rows in the used range
string customerNumber;
string amount;
int i = 0;
decimal dAmount = 0;
bool runProcess = true;
bool hasHeader = false;
string cellValue;
foreach (Excel.Range row in usedRange.Rows)
{
i++;
// Column 1 is customer number
// THE FOLLOWING LINE RETURNS NULL STARTING AT ROW 144
cellValue = row.Cells[i, 1].Value2 == null ? "" : row.Cells[i, 1].Value2.ToString();
if (!(cellValue.Length >= 5 && cellValue.Length <= 20))
{
MessageBox.Show(cellValue + " Must be between 5 and 20 Characters - File Will Not Be Processed Row#" + i.ToString());
runProcess = false;
}
}
// run process
// release EXCEL
我认为这与范围对象的大小有关。我试着将foreach替换成这个,它成功了(对我来说,空值出现在第102行)
int maxRows=usedRange.Rows.Count;
对于(int i=1;i=5&&cellValue.Length是来自错误行的样本数据,还是只是来自电子表格中的一般数据?它来自错误行。我已将好行的数据复制到错误行中,错误仍然存在。电子表格中的所有值是以44开始还是以开始de>44
您遇到了错误吗?只是想缩小范围:-)为了跟进@Mis的答案,您的所有值是否都超过了15位的精度?忘记这个问题,错过了您的评论。非常感谢。我将尝试一下,并让您知道结果。
4492605768531895 15.95
4492605768536544 19.95
4492605768565459 11.95
4492605739542347 14.95
4492605768635795 25.95
int maxRows = usedRange.Rows.Count;
for (int i=1;i<=maxRows;i++)
{
// Column 1 is customer number
// THE FOLLOWING LINE RETURNS NULL STARTING AT ROW 144
cellValue = xlWorkSheet.Cells[i, 1].Value2 == null ? "" : xlWorkSheet.Cells[i, 1].Value2.ToString();
if (!(cellValue.Length >= 5 && cellValue.Length <= 20))
{
MessageBox.Show(cellValue + " Must be between 5 and 20 Characters - File Will Not Be Processed Row#" + i.ToString());
runProcess = false;
}
}