我编写了一些从excel读取数据的代码,并在消息框中显示数据。我从网站上获取了该代码。当我运行相同的操作时,我会在两个特定行中出现一些错误
我遇到错误的行如下
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());
}
}
完整代码如下
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace ExcelReader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"D:/C.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());
}
}
}
}
}
有人可以帮我解决这段代码的正确解决方案吗?
答案 0 :(得分:0)
替换
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
与
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{