简体   繁体   English

读取带有C#错误的动态Excel文件

[英]Reading an dynamic Excel File with C# error

I am trying to read an excel file with C# and display every cell in the sheet inside a messagebox using the messagebox.Show() method. 我正在尝试使用C#读取excel文件,并使用messagebox.Show()方法在messagebox.Show()的工作表中显示每个单元格。 Problem is that my excel file has 5 rows and 3 columns. 问题是我的excel文件有5行3列。 here is my excel sheet: http://postimg.org/image/xts9n1kif . 这是我的Excel工作表: http : //postimg.org/image/xts9n1kif

It displays everything until "roof" and after that stops leaving behind "light" and "iron", but if i fill the stuff3 column it reads everything perfectly fine. 它显示所有内容,直到“屋顶”,然后停止显示“光”和“铁”,但是如果我填充stuff3列,则一切都很好。 As is my case, the file may change. 按照我的情况,文件可能会更改。 It may have more columns or rows in it, and some of them may be empty. 它可能有更多的列或行,其中一些可能为空。

Any idea why it is not working? 知道为什么它不起作用吗?

Here is my code: 这是我的代码:

using System;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace ReadFromExcell
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += new System.EventHandler(this.Form1_Load);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Excel.Application xlApp = new Excel.Application();
            Excel.Workbook xlWorkbook = xlApp.Workbooks.Open("C:\\Users\\User1\\Desktop\\ItemDB.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());
                }
            }
            //Close the excel file after reading it.
            xlWorkbook.Close();
        }



    }
}

Most likely what happens in your code is that when the loop hits cell C4 (which is empty) xlRange.Cells[i, j].Value2 becomes null . 代码中最有可能发生的情况是,当循环到达单元格C4 (为空)时, xlRange.Cells[i, j].Value2变为null

Trying to invoke the ToString() method (or any other method, for that matter) on a null reference will cause a NullReferenceException . 尝试在null引用上调用ToString()方法(或其他任何方法)将导致NullReferenceException

Change your code inside your loop from... 从...更改循环内的代码...

MessageBox.Show(xlRange.Cells[i, j].Value2.ToString());

...to something like that: ...像这样:

MessageBox.Show( (xlRange.Cells[i, j].Value2 ?? "<no value>").ToString() );

The ?? ?? operator is handy in this situation. 在这种情况下, 操作员很方便。 If the expression on the left side of ?? 如果表达式在??的左侧 (that is xlRange.Cells[i, j].Value2 ) results in a null value, the ?? (即xlRange.Cells[i, j].Value2 )得出值,即 operator returns the value on the right-hand side of ?? 运算符返回??右侧的值。 instead. 代替。


(The cell C4 could contain a number of white-space characters, in which case the cell's value would not be null . But a cell with just a number of white-space characters is a rather unusual and rare occurrence.) (单元格C4可以包含多个空格字符,在这种情况下,该单元格的值不能为null 。但是,只有多个空格字符的单元格是非常罕见的情况。)

Now Try this.. 现在尝试这个。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM