gpt4 book ai didi

c# - 从 Excel 电子表格读取数据 - 无法对空引用执行运行时绑定(bind)

转载 作者:行者123 更新时间:2023-11-30 19:44:55 24 4
gpt4 key购买 nike

我有下面的代码从 excel 文件中读取数据,我遇到的问题是当我尝试读取范围数据时,我在这一行收到异常“无法对空引用执行运行时绑定(bind)”

if (Int32.TryParse(xlRange.Cells[1, 4].Value2.ToString(), out value)) 

我想知道的是我如何正确访问范围内的信息。提前致谢

void ReadFromExcelToGrid2(String fileNameString)
{
try
{
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fileNameString);
//get list of worksheets associated with the current workbook
Microsoft.Office.Interop.Excel.Sheets worksheets = xlWorkbook.Worksheets;
//list the work books in a dropdownlist
IDictionary<int, String> sheets = new Dictionary<int, String>();
foreach (Microsoft.Office.Interop.Excel.Worksheet displayWorksheet in xlWorkbook.Worksheets)
{
sheets.Add(displayWorksheet.Index, displayWorksheet.Name);
}
cmbWorksheets.DataSource = new BindingSource(sheets, null);;
cmbWorksheets.DisplayMember = "Value";
cmbWorksheets.ValueMember = "Key";

Microsoft.Office.Interop.Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[4]; // assume it is the first sheet
Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange; // get the entire used range
int value = 0;
if (Int32.TryParse(xlRange.Cells[1, 4].Value2.ToString(), out value)) // get the F cell from the first row
{
int numberOfColumnsToRead = value * 4;
for (int col = 7; col < (numberOfColumnsToRead + 7); col++)
{
Console.WriteLine(xlRange.Cells[1, col].Value2.ToString()); // do whatever with value
}
}
}
catch (Exception ex)
{

throw ex;
}
}

最佳答案

if (xlRange.Cells[row, 1].Text == "")
{
xlRange.Cells[row, 1].value = "Blank";
}

上面的代码将解决这个问题。但是 Blank 不会出现在单元格中。但它会让你走得更远。基本上 C#/Excel 不喜欢 null

关于c# - 从 Excel 电子表格读取数据 - 无法对空引用执行运行时绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11593628/

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