这是我第一次用c#访问和读取excel文件(xlsx)。我遇到问题,错误是:没有为一个或多个必需的参数指定值
下面是我的代码:
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文件:

但是运行代码会给出一个错误:没有为一个或多个必需的参数赋值。
发布于 2011-07-12 23:46:05
好的,我找到了一种在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 Object Library的引用,该引用可以在COM选项卡下找到...如果你想阅读多个文本,只需使用rCnt或cCnt的循环和增量值...如果你想写入单元格,我认为可以这样做:
(range.Cells[rCnt, cCnt] as Excel.Range).Value2 = value;这是all...hope,这会帮助其他人
发布于 2011-07-10 18:45:39
从我拥有的一些旧代码中可以看出,语法应该是:
ExcelQuery = "SELECT * FROM A1:Q10000";这意味着您不必指定工作表名称,它将始终从第一个工作表或默认工作表中提取,并且您还必须指定您选择的列的范围。
发布于 2011-07-11 10:44:44
我相信您查询中的A1就是问题所在。要进行测试,只需尝试以下操作,并查看它是否消除了错误...
ExcelQuery = "SELECT * FROM [Sheet1$]";如果您想选择特定的列,则使用HDR=YES (在conn字符串中)。
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Temp\Class Schedules.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";这表示工作表的第一行包含列名。所以它要求您的工作表以这种方式格式化,但然后您可以选择特定的列…
ExcelQuery = "SELECT [Time] FROM [Sheet1$]";https://stackoverflow.com/questions/6640180
复制相似问题