Solved

Implementing IEnumerable

Posted on 2013-01-23
10
341 Views
Last Modified: 2013-04-02
Hi guys,

Im trying to implement the code below and im having trouble. Basically I want to use the excel datareade to rad the excel file then store the values and use them as the itemsource of a datagrid. My code is below...

  public class test : IEnumerable<Employee>
    {

        public IEnumerable<Employee> ReadFile(string filePath)
        {
            var employees = new List<Employee>();
            var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
            // Want to be able to handle .xls or .xlsx file formats
            var excelReader = filePath.Contains(".xlsx")
                                  ? ExcelReaderFactory.CreateOpenXmlReader(stream)
                                  : ExcelReaderFactory.CreateBinaryReader(stream);

            excelReader.IsFirstRowAsColumnNames = true;

            excelReader.Read(); //skip first row
            while (excelReader.Read())
            {
                employees.Add(new Employee
                {
                    Name = excelReader.GetString(0),
                    Address = excelReader.GetString(1),
                    City = excelReader.GetString(2),
                    State = excelReader.GetString(3),
                    PostalCode = excelReader.GetString(4)
                });
            }

            excelReader.Close();

            return employees;
        }

    }

Open in new window


Its highlighting 'Employee' and saying.. The type or namespace 'Employee' could not be found (are you missing a using directive or an assembly reference? Does this actually need its own namespace?

Thanks,
Dean
0
Comment
Question by:deanlee17
  • 4
  • 4
  • 2
10 Comments
 
LVL 22

Expert Comment

by:ambience
Comment Utility
The type Employee must be known to the compiler when compiling this code.

If Employee resides in another assembly then make sure you have added a reference to the assembly. (check References under project node)

If Employee has a namespace different than the one that class 'test' has then you need to add a using statement at the top, for example

using MyNamespace.Models;

(assuming Employee has namespace MyNamespace.Models).
0
 
LVL 14

Expert Comment

by:athomsfere
Comment Utility
Wouldn't it be just as easy / effective to bind the datagrid to the excel document and use LINQ?
0
 

Author Comment

by:deanlee17
Comment Utility
athomsfere, maybe? Do you have an example? Baring in mind this could be varying excel documents not just the one.

ambience, getting my head around your post.
0
 

Author Comment

by:deanlee17
Comment Utility
Ok here is my complete code, its the first thing ive tried to do in this project.....

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Excel;

namespace DragDrop
{
 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

    }


    public class test : IEnumerable<Employee>
    {

        public IEnumerable<Employee> ReadFile(string filePath)
        {
            var employees = new List<Employee>();
            var stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
            // Want to be able to handle .xls or .xlsx file formats
            var excelReader = filePath.Contains(".xlsx")
                                  ? ExcelReaderFactory.CreateOpenXmlReader(stream)
                                  : ExcelReaderFactory.CreateBinaryReader(stream);

            excelReader.IsFirstRowAsColumnNames = true;

            excelReader.Read(); //skip first row
            while (excelReader.Read())
            {
                employees.Add(new Employee
                {
                    Name = excelReader.GetString(0),
                    Address = excelReader.GetString(1),
                    City = excelReader.GetString(2),
                    State = excelReader.GetString(3),
                    PostalCode = excelReader.GetString(4)
                });
            }

            excelReader.Close();

            return employees;
        }

    }
}

Open in new window

0
 
LVL 14

Expert Comment

by:athomsfere
Comment Utility
Looks like a tutorial for LINQ and Excel is of google code.

http://code.google.com/p/linqtoexcel/
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 22

Expert Comment

by:ambience
Comment Utility
Looing at your complete code there is no Employee and no import (using statement). Are you missing out something? Could it be that you have to write the Employee class yourself, but havent yet?

Should be simple

public class Employee
{
     public string Name{ get; set; }
     public string Address { get; set; }
     public string City { get; set; }
     ...
}
0
 

Author Comment

by:deanlee17
Comment Utility
Yes you are correct I needed to create the Employee Class.

However im just having a quick look at LinqToExcel as my project will have other LINQ queries as well. My code is below but im getting the errors

'Error      1      Program 'c:\Users\dean.lee\Desktop\DragDropSpreadsheet\DragDropSpreadsheet\obj\Debug\DragDropSpreadsheet.exe' has more than one entry point defined: 'DragDropSpreadsheet.Program.Main(string[])'.  Compile with /main to specify the type that contains the entry point.      C:\Users\dean.lee\Desktop\DragDropSpreadsheet\DragDropSpreadsheet\MainWindow.xaml.cs      31      21      DragDropSpreadsheet
'

and

'Error      2      Program 'c:\Users\dean.lee\Desktop\DragDropSpreadsheet\DragDropSpreadsheet\obj\Debug\DragDropSpreadsheet.exe' has more than one entry point defined: 'DragDropSpreadsheet.App.Main()'.  Compile with /main to specify the type that contains the entry point.      C:\Users\dean.lee\Desktop\DragDropSpreadsheet\DragDropSpreadsheet\obj\Debug\App.g.cs      62      28      DragDropSpreadsheet
'

I have copied the example exactly, any ideas where i have gone wrong with the entry point?...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LinqToExcel;
using Remotion.Data.Linq;



namespace DragDropSpreadsheet
{
    public class Person
    {
        public string Name { get; set; }
        public string Address { get; set; }
        public string Postcode { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var excel = new ExcelQueryFactory();
            excel.FileName = "WHATEVER";

            var people = from x in excel.Worksheet<Person>()
                         select x;
        }
    }
}

Open in new window

0
 
LVL 22

Accepted Solution

by:
ambience earned 500 total points
Comment Utility
It looks like you have added another source file to the same project and that has Main.

You can temporarily exclude other files from the project or better create another project and add just this file to it.
0
 
LVL 22

Expert Comment

by:ambience
Comment Utility
OR goto project properties and define an entry point, from the dropdown list.
0
 

Author Comment

by:deanlee17
Comment Utility
Ok done that and seems to work. Any idea how to add a file location? That example only seems to hold filename?

Thanks.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now