gpt4 book ai didi

c# - "No value given for one or more required parameters"访问Excel电子表格

转载 作者:太空宇宙 更新时间:2023-11-03 14:15:41 26 4
gpt4 key购买 nike

这是我第一次使用 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文件:

enter image description here

但是运行代码会给我一个错误:没有为一个或多个必需参数提供值。

最佳答案

好的,我找到了一种在 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 选项卡下找到...如果你想阅读多篇文章,只需使用 for 循环和 rCnt 或 cCnt 的增量值...如果你想写入单元格,我认为可以这样做:

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

就这些了...希望这对其他人有帮助

关于c# - "No value given for one or more required parameters"访问Excel电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6640180/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com