To be able to import and edit an Excel document you need to open it first.
The code that you have so far does not even specify an Excel document to work
with.
Lets start at the beginning. I assume you have added a reference to the
Microsoft Excel Object Library before you started? If that doesn't sound
familiar then you need to download the Microsoft Office XP PIAs before you
can go any further (Assuming you are using XP, if not then the Office PIA for
your OS). When I wrote my first program to control an Excel document I found
a lot of useful info at the following url:
http://support.microsoft.com/kb/311452/
This one is also good and is more specific to your needs:
http://support.microsoft.com/kb/302084/
Here is some code I wrote to get you started:
using System;
using Excel = Microsoft.Office.Interop.Excel;
namespace ConsoleApplication2
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
DoWork();
}
public static void DoWork()
{
string workbookPath = @"C:\MyDocument.xls";
if (!System.IO.File.Exists(workbookPath))
{
Console.WriteLine("The source file does not exist. Press any key to
exit.");
Console.ReadLine();
return;
}
Excel.ApplicationClass excelApp = null;
Excel.Workbook excelWorkbook = null;
try
{
// Get an Excel instance and open the file
excelApp = new Excel.ApplicationClass();
excelWorkbook = excelApp.Workbooks.Open(workbookPath, 0, false, 5, "", "",
false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false,
false);
// Get the worksheet with data
Excel.Sheets excelSheets = excelWorkbook.Worksheets;
string mySheet = "Sheet X";
Excel.Worksheet excelWorksheet =
(Excel.Worksheet)excelSheets.get_Item(mySheet);
try
{
if (!((Excel.Range)excelWorksheet.get_Range("B1", "B1")).Text.Equals(""))
{
// Display the text in the cell B1
Console.WriteLine(((Excel.Range)excelWorksheet.get_Range("B1",
"B1")).Text);
}
}
catch (Exception ex)
{
Console.WriteLine("An exception occurred while reading from the Excel
document: " + ex.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine("An exception occurred while setting up the
environment: " + ex.ToString());
}
finally
{
// Exit everything
if (excelWorkbook != null)
{
excelWorkbook.Close(false, System.Reflection.Missing.Value, false);
excelWorkbook = null;
}
if (excelApp != null)
{
excelApp.Quit();
excelApp = null;
}
// Clean up
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
}
Adrian.