please look at my code below, I tried to get the excel worksheet cells values with C#. However when I checked the values in the immediate window, they are not match with the real values at all. Some are null. Why? Thanks for advice.
string fname;
int nRows;
int nCols;
private void button1_Click(object sender, EventArgs e)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWookSheet1;
Excel.Range xlRange;
openFileDialog1.Filter = "(*.xls)|*.xls|(*.xlsx)|*.xlsx";
openFileDialog1.Title = "Select an excel file";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
fname = openFileDialog1.FileName;
System.IO.FileInfo fi = new System.IO.FileInfo(fname);
string ext = fi.Extension.ToString();
xlApp = new Excel.ApplicationClass();
string parameter;
if (ext == ".xls")
parameter = "5";
else
parameter = "51";
xlWorkBook = xlApp.Workbooks.Open(fname, 0, true, parameter, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWookSheet1 = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
object misValue = System.Reflection.Missing.Value;
xlRange = xlWookSheet1.UsedRange;
if (xlRange != null)
{
nRows = xlRange.Rows.Count;
nCols = xlRange.Columns.Count;
xlRange = (Microsoft.Office.Interop.Excel.Range)xlWookSheet1.Cells[nRows, nCols];
}
Dictionary<int, List<int>> dict = new Dictionary<int, List<int>>();
List<string> list1 = new List<string>();
for (int i = 1; i < nCols; i++)
{
string temp = (string)(xlRange.Cells[1, i] as Excel.Range).Value2;
// wrong values from temp
list1.Add(temp);
}