1

I am trying to open an Excel file located on my local computer and take out a few values from it. The values are a mix of strings and numbers located in different cells. The Excel file will be opened using openFileDialog. I am using C# and developing a desktop application (WPF). This is the code I am implementing:

     Excel.Application excelApp = new Excel.Application();
        string workbookPath = "C:/Users/b_prashanth/Documents/26. Workload Modeling generic template.xlsx";
        Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);
        Excel.Sheets excelSheets = excelWorkbook.Worksheets;
        string currentSheet = "Sheet1";
        Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelSheets.get_Item(currentSheet);
        Excel.Range excelCell =
    (Excel.Range)excelWorksheet.get_Range("A1", "A1");
3
  • Please add an example of what you've tried or this will be closed. Commented Sep 18, 2015 at 4:08
  • Does the client that will run application have excel installed? Commented Sep 18, 2015 at 4:14
  • Yes excel is installed in the client. Commented Sep 18, 2015 at 4:32

3 Answers 3

1

I think, OpenXML SDK should help you.
http://www.codeproject.com/Articles/670141/Read-and-Write-Microsoft-Excel-with-Open-XML-SDK
It's available via nuget - DocumentFormat.OpenXML, and here you can find all classes and algorithms, what you needed

Sign up to request clarification or add additional context in comments.

Comments

1

What about something like this? What's the problem you've faced?

Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".xlsx";
bool? result = dlg.ShowDialog();

if (result != true) return;

string workbookPath = dlg.FileName;

Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);
Excel.Worksheet sheet = excelWorkbook.Sheets["Sheet1"] as Excel.Worksheet; 

if (sheet == null) return;

Excel.Range range = sheet.get_Range("A1", Missing.Value)

var yourValue = range.Text;

2 Comments

I tried this. I get an error on the line "Excel.Worksheet sheet = excelWorkbook.Sheets["Sheet1"] as Excel.Worksheet;" saying "An unhandled exception of type 'System.Runtime.InteropServices.COMException' occurred in WpfApplication2.exe"... Also, "missing.value" is not available. Instead i am using "Type.missing".
Not sure what the problem is then because this code and your code both work on my machine.
0

Instead of Office interop, which requires Office to be installed on the machine, you could access the Excel sheet like a database using the ADO driver.

This has been documented here many times and would be very easy.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.