C#拾取错误数量的Excel行,空值错误

我是C#的新手,所以请原谅我的代码中的愚蠢的错误:我正在循环通过Excel文件时出现以下错误:

附加信息:无法在空引用上执行运行时绑定

我收集到了太多行(Excel文件只有2行,最后find6行?)的问题,到了第三行时,就会发生错误。 我已经打开了Excel文件,并在第二行之后删除了很多行,但它不断出现相同的问题。 正如我在这里,我想问一下下面的问题:

  1. 我怎么去解决上述错误。
  2. 如何输出同一行上的所有值,以及何时更改行计数,进入下一行中的下一行并开始写入?

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.OleDb; using System.IO; using System.Text.RegularExpressions; using Excel = Microsoft.Office.Interop.Excel; namespace KTypeLookUp { public partial class Form1 : Form { FileStream ostrm; StreamWriter writer; TextWriter oldOut = Console.Out; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) {//Select Input File Button String textPath = @"C:\AAAtemp\export.txt"; OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Excel Files(*.xls)|*.xls|All Files|*.*"; if (ofd.ShowDialog() == DialogResult.OK) {//Read and display Excel file string path = ofd.FileName.ToString(); textBox3.Text = path; OleDbConnection conn = new OleDbConnection(); conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\";"; OleDbCommand command = new OleDbCommand ( "SELECT * FROM [Sheet1$]", conn ); DataSet dataset = new DataSet(); OleDbDataAdapter adapter = new OleDbDataAdapter(command); adapter.Fill(dataset); dataGridView1.DataSource = dataset.Tables[0]; Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path); Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1]; Excel.Range xlRange = xlWorksheet.UsedRange; int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count; try { ostrm = new FileStream(textPath, FileMode.OpenOrCreate, FileAccess.Write); writer = new StreamWriter(ostrm); } catch (Exception ex) { ex.ToString(); MessageBox.Show("", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); return; } for (int i = 1; i <= rowCount; i++) { for (int j = 1; j <= colCount; j++) { Console.SetOut(writer); Console.WriteLine(xlRange.Cells[i, j].Value2.ToString()); } } writer.Close(); ostrm.Close(); MessageBox.Show("Text file created", "My Application", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk); } } private void textBox3_TextChanged(object sender, EventArgs e) {//Text box to display path textBox3.ReadOnly = true; } } } 

您的问题可能与使用UsedRange确定电子表格中的行数有关。

当你知道它包含了什么,并保持电子表格处于正确的状态时, UsedRange非常有用。 具体来说, UsedRange将包括格式化但没有数据的单元格。 该格式可能包括不可见的细节,如对默认字体的更改。

如果你想testing这个,你需要删除所有你想包含的行之下的行。 在评论中,你提到这只有2行。 我会select第3行(点击行标签)并使用CTRL + SHIFT + DOWNselect下面的所有行,然后删除它们(CTRL + MINUS)。 您的UsedRange然后应该调整为只有2行总数。

或者,根据您的数据,您可以使用其他一些技术来确定您拥有的数据行数。 如果数据是连续的(整行/列没有间隙),可以使用CurrentRegion获取数据的“块”。