1

I have a c# application which reads data from an excel file.

i used

Range xlRng = (Range)workSheet.get_Range("A1:B6", Missing.Value);

this to read value from A1 to B6 cells

if i gave a range i need to read value to a dictionary and the key name must be cell index and the value must be corresponding cell value

Key Value

A1 Value1

B1 Value2

A2 Value3

B2 Value4

2 Answers 2

3

You could also try this

Excel.Range xlRng = (Excel.Range)workSheet.get_Range("A1:B6", Type.Missing);
Dictionary<string, string> dic = new Dictionary<string, string>();
foreach (Excel.Range cell in xlRng)
{

    string cellIndex = cell.get_AddressLocal(false, false, Excel.XlReferenceStyle.xlA1, Type.Missing, Type.Missing);
    string cellValue = Convert.ToString(cell.Value2);
    dic.Add(cellIndex, cellValue);
 }

If you would use Excel namespace as same as me, so don't forget to import namespace

using Excel = Microsoft.Office.Interop.Excel;

I hope this will be helpfull

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

3 Comments

thank u.. string cellValue = cell.Value; modified this as string cellValue = cell.Value2; so please edit your answer,thank u
please modify your answer
Oh, I'm so sorry for late, cell.Value works for me. Anyway, I've changed my answer as your suggestion. Thank you.
1

have you tried EPPlus?

Here is sample code that would do what you want:

void Main()
{
    var existingFile = new FileInfo(@"c:\temp\book1.xlsx");
    // Open and read the XlSX file.
    using (var package = new ExcelPackage(existingFile))
    {
        // Get the work book in the file
        ExcelWorkbook workBook = package.Workbook;
        if (workBook != null)
        {
            if (workBook.Worksheets.Count > 0)
            {
                // Get the first worksheet
                ExcelWorksheet sheet = workBook.Worksheets.First();

                // read some data
                Dictionary<string,double> cells = (from cell in sheet.Cells["A1:B6"] 
                            where cell.Start.Column == 1
                            select sheet.Cells[cell.Start.Row,cell.Start.Column,cell.Start.Row,2].Value)
                            .Cast<object[,]>()
                            .ToDictionary (k => k[0,0] as string, v => (double)(v[0,1]));

                //do what you need to do with the dictionary here....!
            }
        }
    }

}

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.