Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Data.OleDb;
- using System.Reflection;
- namespace Sync.Core
- {
- public class ExcelReaderEngine<T> where T: class, new()
- {
- private const string JET_CONNECTION_STRING =
- "Provider=Microsoft.Jet.OLEDB.4.0;Data source={0};Extended Properties=Excel 8.0;;Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;MaxScanRows=0;\"";
- private const string ACE_CONNECTION_STRING =
- "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1;MaxScanRows=0;\"";
- private const string SELECT_STATEMENT = "SELECT * FROM [{0}$]";
- IEnumerable<FieldInfo> _fields = null;
- public ExcelReaderEngine()
- {
- _fields = typeof(T).GetFields(BindingFlags.Instance | BindingFlags.Public).OrderBy(i => i.MetadataToken);
- }
- public IEnumerable<T> ReadData(OleDbConnection conn, OleDbCommand comm)
- {
- List<T> result = new List<T>();
- var reader = comm.ExecuteReader();
- while (reader.Read())
- {
- var index = 0;
- var entity = new T();
- foreach (var field in _fields)
- {
- var value = reader.GetValue(index);
- if (value is DBNull) { value = null; }
- index++;
- if (field.FieldType == typeof(String))
- {
- field.SetValue(entity, value);
- }
- else if (field.FieldType == typeof(Int32))
- {
- field.SetValue(entity, value != null ? Int32.Parse(value.ToString()) : 0);
- }
- else if (field.FieldType == typeof(Double))
- {
- field.SetValue(entity, value != null ? Double.Parse(value.ToString()) : 0.0);
- }
- else if (field.FieldType == typeof(DateTime))
- {
- field.SetValue(entity, value != null ? DateTime.Parse(value.ToString()) : new DateTime());
- }
- }
- result.Add(entity);
- }
- return result;
- }
- /// <summary>
- /// Returns OPENED connection to Excel file.
- /// </summary>
- /// <param name="file">File name</param>
- /// <returns>Connection</returns>
- private OleDbConnection Connect(string file)
- {
- OleDbConnection result = null;
- // This doesn't look so nice. But it's the only way to leap over MS Excel driver problems.
- try
- {
- result = new OleDbConnection(String.Format(ACE_CONNECTION_STRING, file));
- result.Open();
- }
- catch
- {
- try
- {
- result = new OleDbConnection(String.Format(JET_CONNECTION_STRING, file));
- result.Open();
- }
- catch
- {
- throw;
- }
- }
- return result;
- }
- public IEnumerable<T> GetData(string file, string page)
- {
- using (var conn = Connect(file))
- {
- using (var comm = conn.CreateCommand())
- {
- comm.CommandText = String.Format(SELECT_STATEMENT, page);
- return ReadData(conn, comm);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment