“没有给出一个或多个必需参数的值”访问Excel电子表格

它是我第一次访问和读取Excel文件(XLSX)与C#..我有问题,错误是:没有给出一个或多个所需的参数值

下面是我的代码:

private void button5_Click(object sender, EventArgs e) { string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Class Schedules.xlsx;Extended Properties=""Excel 12.0;HDR=NO;"""; string ExcelQuery; ExcelQuery = "SELECT A1 FROM [Sheet1$]"; OleDbConnection ExcelConnection = new OleDbConnection(ConnectionString); ExcelConnection.Open(); OleDbCommand ExcelCommand = new OleDbCommand(ExcelQuery, ExcelConnection); OleDbDataReader ExcelReader; ExcelReader = ExcelCommand.ExecuteReader(); //error happens here while (ExcelReader.Read()) { MessageBox.Show((ExcelReader.GetValue(0)).ToString()); } ExcelConnection.Close(); } 

因为这是我第一次,我只是想读取A1的内容,下面是我的Excel文件:

在这里输入图像说明

但运行代码会给我一个错误:没有给出一个或多个所需的参数值。

好吧,我find了一种方法来读取特定的单元格在C#中….

位置rCnt=1,cCnt=1是excel中的A1

  private void button9_Click(object sender, EventArgs e) { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range range; string str; int rCnt = 1; // this is where you put the cell row number int cCnt = 1; // this is where you put the cell column number xlApp = new Excel.ApplicationClass(); xlWorkBook = xlApp.Workbooks.Open(@"C:\Class Schedules.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; str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2; //you now have the value of A1. xlWorkBook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); } private void releaseObject(object obj) { try { System.Runtime.InteropServices.Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; MessageBox.Show("Unable to release the Object " + ex.ToString()); } finally { GC.Collect(); } } 

一定要有:

  using Excel = Microsoft.Office.Interop.Excel; 

并添加一个名为Microsoft Excel对象库的项目,可以在COM选项卡下find一个引用…如果你想要读取多个文本,只需使用for循环和递增值rCnt或cCnt …如果你想写进入细胞,我认为这可以做到这一点:

 (range.Cells[rCnt, cCnt] as Excel.Range).Value2 = value; 

这是所有…希望这将有助于其他人

从我看过的一些旧代码中,语法应该是:

 ExcelQuery = "SELECT * FROM A1:Q10000"; 

这意味着您不必指定工作表名称,它将始终从第一个或默认工作表中取出,您还必须指定所选列的范围。

我相信在你的查询A1是问题。 要testing只是尝试以下,看到它消除了错误…

 ExcelQuery = "SELECT * FROM [Sheet1$]"; 

如果你想select特定的列,然后使用HDR = YES(在你的连接string)。

 string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Class Schedules.xlsx;Extended Properties=""Excel 12.0;HDR=YES;"""; 

这表示表格的第一行包含列名称。 所以它需要你的工作表被格式化,但是你可以select特定的列…

 ExcelQuery = "SELECT [Time] FROM [Sheet1$]";