gpt4 book ai didi

c# - "Cannot perform runtime binding on a null reference"读取/显示Excel

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

我准备了一个简单的代码,用于将 excel 文件读取为 c# Wpf 格式。

但是我得到了错误:

{"Cannot perform runtime binding on a null reference"}.

下面是代码....

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("Book1.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;

for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j<= colCount; j++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}
}
}
}

最佳答案

不要使用 .ToString() 方法。当值为null时会引发空引用异常。

使用可以使用Convert.ToString()

关于c# - "Cannot perform runtime binding on a null reference"读取/显示Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31133141/

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