我的项目是打开excel文件并在C#中逐行读取,但我的excel参考文件存在一些空行
例如,第一行和第二行不是空的(没有单元格(,但第三行、第四行和第五行的所有单元格都是
空,然后下一行的单元格不空等等。现在当我的代码在for just Reads 中运行时
只有文件的前几行是满的,一旦到达第一行,就完全空了
它脱离了循环,而读取文件还没有结束。为什么会发生这种情况?如何修复?
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;
string str;
string table = null;
int rCnt;
int cCnt;
int rw = 0;
int cl = 0;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(@"C:UsersmostafaheydarsanaDesktopmp.xlsx", 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);
range = xlWorkSheet.UsedRange;
rw = range.Rows.Count;
cl = range.Columns.Count;
string s = "'nbn";
string table_row = null;
int io = 0;
string new_str = null;
string question_field = null;
int peymaeshrowaforaddquestioha;
try
{
StreamWriter sw = new StreamWriter("C:\Users\user1\Desktop\Test.txt");
for (rCnt = 1; rCnt <= rw; rCnt++)
{
if (range.Cells[rCnt, 1].Value != null)
{
sw.WriteLine("question is ( " + question_field + s[0] + "," + new_str + "');", io++);
MessageBox.Show("rCnt is " + rCnt + "quesstion_field is insert in file ***" + question_field + "***");
question_field = null;
new_str = null;
new_str += s[0] + range.Cells[rCnt, 1].Value2.ToString() + s[0] + "," + s[0] + range.Cells[rCnt, 2].Value2.ToString() + s[0] + "," + s[0] + range.Cells[rCnt, 3].Value2.ToString() + s[0];
question_field += range.Cells[rCnt, 4].Value2.ToString();
}
else if(range.Cells[rCnt, 1].Value == null)
{
question_field += range.Cells[rCnt, 4].Value2.ToString();
MessageBox.Show("rCnt is " + rCnt + "quesstion_field is ***" + question_field + "***");
peymaeshrowaforaddquestioha = rCnt + 1;
}
}
sw.Close();
}
catch (Exception ec)
{
Console.WriteLine("Exception: " + ec.Message);
}
finally
{
Console.WriteLine("Executing finally block.");
}
xlWorkBook.Close(true, null, null);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
}
在使用MS OpenXML库创建Excel输出时遇到了很多困难,我在NuGet中发现了ClosedXML包,这是一种更好、更容易的方法。这很可能也可以解决你阅读Excel的问题。
根据我的测试,问题是当您尝试访问null单元格时,会出现异常"无法对null引用执行运行时绑定"。
根据引用无法对空引用执行运行时绑定-空Excel单元格,您可以尝试修改以下代码。
更改
question_field += range.Cells[rCnt, 4].Value2.ToString();
进入:
question_field +=Convert.ToString(range.Cells[rCnt, 4].Value2);
它对我有用。