OleDbDataReader从Excel电子表格中读取空白行

不知道是怎么回事,因为我之前使用OleDbDataReader从Excel电子表格中提取数据,但是突然间,我的C#批处理作业并没有通过while(_reader.Reader())循环在空行停止。

这里是我正在使用的C#代码。 我只是试图把所有的logging从Excel电子表格中取出,然后循环浏览数据。 不过由于某些原因, _reader.Read()_reader.Read()函数都会返回true

  private static OleDbDataReader _reader; static void Main(string[] args) { string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= \\prdhilfs03\l&i-sales&mkt\WORKAREA\Agencyservices\Shared\AIC\Analysts_and_Reporting\Realignments\2014\MassUpdateTesting\Validate\ZipCodeTest.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'"; string queryString = "SELECT * FROM [Query1$]"; Validation validation; ZipCodeTerritory record; bool flag = true; try { Stopwatch watch = new Stopwatch(); watch.Start(); using (OleDbConnection connection = new OleDbConnection(connString)) { //Set connection objects to pull from spreadsheet OleDbCommand command = new OleDbCommand(queryString, connection); connection.Open(); _reader = command.ExecuteReader(); //Instantiate validation object with zip and channel values _allRecords = GetRecords(); validation = new Validation(); validation.SetLists(_allRecords); while (_reader.Read()) { record = new ZipCodeTerritory(); record.ChannelCode = _reader[0].ToString(); record.DrmTerrDesc = _reader[1].ToString(); record.IndDistrnId = _reader[2].ToString(); record.StateCode = _reader[3].ToString().Trim(); record.ZipCode = _reader[4].ToString().Trim(); record.EndDate = Convert.ToDateTime(_reader[5].ToString()); record.EffectiveDate = Convert.ToDateTime(_reader[6].ToString()); record.LastUpdateId = _reader[7].ToString(); record.ErrorCodes = _reader[8].ToString(); record.Status = _reader[9].ToString(); record.LastUpdateDate = DateTime.Now; if (string.IsNullOrEmpty(record.LastUpdateId)) { //Add to error list _issues++; _errorList.Add(record, "Missing last update Id"); continue; } if (_reader[10] != DBNull.Value) { record.Id = Convert.ToInt32(_reader[10]); } _errorMsg = validation.ValidateZipCode(record); if (!string.IsNullOrWhiteSpace(_errorMsg)) { _errorList.Add(record, _errorMsg); continue; } else if (flag) { //Separate updates to appropriate list SendToUpdates(record); } //Console.WriteLine(record.Id.ToString()); } 

我发现堆栈溢出这个问题 ,并试图通过更改queryString以下select的答案。 但是,这只是在OleDbCommand运行其.ExecuteReader()方法时引发OleDbException 。 (exception的Message属性显示“没有给出一个或多个必需参数的值”)

SELECT * FROM [Query1$] WHERE NOT ([ChannelCode] = '' and [DrmTerrDec] = '' and [StateCode] = '' and [ZipCode] = '' and [EndDate] = '' and [EffectiveDate] = '')

编辑

只是在while循环内添加了所有的代码。

这帮助了我

 dataTable = dataTable.Rows.Cast<DataRow>().Where(row => !row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).CopyToDataTable();e 

采取从https://stackoverflow.com/a/9233678