Reputation: 1988
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
Upvotes: 1
Views: 7681
Reputation: 1265
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
Upvotes: 3
Reputation: 9138
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....!
}
}
}
}
Upvotes: 1