Ok, that make a sence,
then try this code, but change before Excel file name,
shhet name and range address:
Require references to:
Microsoft Excel 12.0 Object Library
and
Microsoft Office 12.0 Object Library
//--------------------------------------------//
#region "Imports"
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
#endregion
public static void ReadExcel()
{
// set file name to read:
string xlFileName = @"c:\Test\dummy.xls";
Excel.Application xlApp;
Excel.Workbook xlBook;
Excel.Sheets xlSheets;
Excel.Worksheet xlSheet;
Excel.Range xlRange;
// get Excel application
xlApp = new Excel.Application();
xlApp.Visible = false;
object miss = Type.Missing;
StringBuilder sb = new StringBuilder();
try
{
// try open workbook as read-only
xlApp.Workbooks.Open(xlFileName, false, true, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss, miss);
xlBook = xlApp.ActiveWorkbook;
xlBook.Saved = true;
xlApp.DisplayAlerts = false;
xlSheets = xlBook.Worksheets;
// few ways to get an Excel sheet
// get sheet by name:
// xlSheet = (Excel.Worksheet)xlSheets.Item["Big Sheet"];
// get sheet by index:
xlSheet = (Excel.Worksheet)xlSheets.Item[1];
// get sheet by name:
// xlSheet = (Excel.Worksheet)xlSheets.get_Item("Big Sheet");
// get sheet by index:
// xlSheet = (Excel.Worksheet)xlSheets.get_Item(1);
// few ways to get an Excel range
// xlRange = (Excel.Range)xlSheet.Range[xlSheet.Cells[1, 1], xlSheet.Cells[5, 6]];
// the same as:
xlRange = (Excel.Range)xlSheet.Range["A1:F5"];// <-- change range address here
// read the whole range:
//object[,] varr = (object[,])xlRange.Value2;
// the same as:
object[,] varr = (object[,])xlRange.Value;
// get sizes of arrary:
int i = varr.GetUpperBound(0);
int j = varr.GetUpperBound(1);
// loop thru array
for (int a = 0; a < i; a++)
{
Excel.Range xlCell;
string cell = "";
for (int b = 0; b < j; b++)
{
//cell index in Excel is non zero-based and starts from 1
xlCell = (Excel.Range)xlRange.Item[a + 1, b + 1];
cell = cell + xlCell.Value.ToString() + "\t";
}
// populate stringbuilder
sb.AppendLine(cell);
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
// close all workbooks
xlApp.Workbooks.Close();
// quit application
xlApp.Quit();
MessageBox.Show(sb.ToString());
}
}
_____________________________________
C6309D9E0751D165D0934D0621DFF27919