1

I have a excel table with 1 sheet. That sheet has headers in row 1. One of the headers is Amount.

I want to read all rows from that header and get the sum of it independently of the number or rows, which is never the same, into a variable of type float.

I'm doing this with c#.

I open the workbook, I get the active sheet and then nothing, I get blocked.

How do I go about this? Rui Martins

2
  • I just sit there looking at it and nothing comes out. I'm blocked. Commented Aug 28, 2012 at 15:06
  • How are you "getting the active sheet"? Does that sheet have something like Columns or Rows? Commented Aug 28, 2012 at 15:11

2 Answers 2

2

You could use OleDB instead of Excel.Interop

string con = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\test.xls;" + 
              "Extended Properties='Excel 8.0;HDR=Yes;'";
using(OleDbConnection c = new OleDbConnection(con))
{
    c.Open();
    string selectString = "SELECT SUM(Amount) FROM [Sheet1$]";
    using(OleDbCommand cmd1 = new OleDbCommand(selectString))
    {
       cmd1.Connection = c;
 var result = cmd1.ExecuteScalar();
       Console.WriteLine(result);
    }
 }

This example use the old Microsoft.Jet.OleDB.4.0 provider, but works equally with the new Microsoft.ACE.OLEDB.12.0

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

3 Comments

In the case of this application. Since the workbook is actually open, I have to use Interop
Don't know, I have tried with workbook open and OleDb works, probably there are some options to prevent sharing of open workbooks.
And there's another thing. I don't know where the file is located. It's the user of the aplication that opens it.
0

Take a look at this article, you should be able to loop through the rows and get the total by adding the cell values altogether.

MSDN article on how to retrieve excel cell values.

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.