Read Excel cell data from c# program

Fordraiders
Fordraiders used Ask the Experts™
on
vs 2008

I have a program written in c#.

On a form is a textbox.
If somehow I could supply a excel workbook and an excel sheet name to the program.

Would it be possible to have the textbox display the cell value I'm on from the Excel sheet ?

possibly some suggested code ?



Thanks
fordraiders
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
The below function will return to you the currently selected cell value. You then put this function in a BackGroudWorker or timer, as u wish...

public string GetDataFromExcel(string FileNameProvided)
{
	Excel.Application l_ExcelApp = default(Excel.Application);
	Excel.Workbook l_Workbook = default(Excel.Workbook);

	try {
		l_ExcelApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
		foreach (Workbook l_wb in l_ExcelApp.Workbooks) {
			if (l_wb.Name == FileNameProvided) {
				l_Workbook = l_wb;
			}
		}
		if ((l_Workbook == null)) {
			throw new Exception();
		}
	} catch (Exception ex) {
		Interaction.MsgBox("Excel File Not opened!");
	}

	return System.Convert.ToString(l_ExcelApp.ActiveCell.Value);
}

Open in new window

see this, its much simpler using ado.net oledb excel data provider:-

http://www.codeproject.com/Articles/8500/Reading-and-Writing-Excel-using-OLEDB

Author

Commented:
2 REALLY GREAT SOLUTIONS

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial