I have a app that reads data from Excel xlsx file to 2D array. Now I would like to sum all values in every row on a button click. First I am trying to get length of each dimension of that array. On this point I am getting error:
Object reference not set to an instance of an object
Can you suggest what to do to avoid this error? Here is my code:
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;
using System.Reflection;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form, IDisposable
{
public Form1()
{
InitializeComponent();
}
string[,] tsReqs;
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"C:/test.xlsx");
Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
Excel.Range xlRange = xlWorksheet.UsedRange;
int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;
string[,] tsReqs = new string[rowCount, colCount];
for (int i = 1; i <= rowCount; i++)
{
for (int j = 1; j <= colCount; j++)
{
string str = xlRange.Cells[i, j].Text;
tsReqs[i - 1, j - 1] = str;
}
}
}
private void button3_Click(object sender, EventArgs e)
{
int riadky = tsReqs.GetLength(0);
int stlpce = tsReqs.GetLength(1);
double sucet = 0;
for (int i = 1; i <= riadky; i++)
{
for (int j = 1; j <= stlpce; j++)
{
double hodnota = Convert.ToDouble(tsReqs[i, j]);
sucet = sucet + hodnota;
}
richTextBox1.Text = sucet.ToString()+"\n";
}
}
}
}