├── .gitattributes
├── src
├── LinqToExcel
│ ├── LinqToExcel.snk
│ ├── Logging
│ │ ├── ILogManagerFactory.cs
│ │ └── ILogProvider.cs
│ ├── Domain
│ │ ├── IContainsUnmappedCells.cs
│ │ ├── RowNoHeader.cs
│ │ ├── StrictMappingException.cs
│ │ ├── IAllowFieldTypeConversionExceptions.cs
│ │ ├── Cell.cs
│ │ └── Row.cs
│ ├── Attributes
│ │ └── ExcelColumnAttribute.cs
│ ├── Query
│ │ ├── TrimSpacesType.cs
│ │ ├── StrictMappingType.cs
│ │ ├── ResultObjectMapping.cs
│ │ ├── ExcelQueryConstructorArgs.cs
│ │ ├── ExcelQueryable.cs
│ │ ├── SqlParts.cs
│ │ ├── OleDbServices.cs
│ │ ├── ProjectorBuildingExpressionTreeVisitor.cs
│ │ ├── ExcelQueryArgs.cs
│ │ ├── SqlGeneratorQueryModelVisitor.cs
│ │ ├── ExcelUtilities.cs
│ │ └── WhereClauseExpressionTreeVisitor.cs
│ ├── License.txt
│ ├── Exceptions
│ │ └── ExcelException.cs
│ ├── LinqToExcel.csproj
│ ├── Extensions
│ │ └── CommonExtensions.cs
│ └── IExcelQueryFactory.cs
├── LinqToExcel.Tests
│ ├── ExcelFiles
│ │ ├── NoHeader.xls
│ │ ├── Companies.xls
│ │ ├── Companies.xlsb
│ │ ├── Companies.xlsm
│ │ ├── Companies.xlsx
│ │ ├── EmptyRows.xls
│ │ ├── NamedRanges.xlsx
│ │ ├── WorksheetNames.xlsx
│ │ ├── NoHeader.csv
│ │ └── Companies.csv
│ ├── CompanyWithCity.cs
│ ├── Transformations.cs
│ ├── CompanyNullable.cs
│ ├── Company.cs
│ ├── CompanyNameWithUnmappedCells.cs
│ ├── CompanyWithColumnAnnotations.cs
│ ├── CompanyGoodWithAllowFieldTypeConversionExceptions.cs
│ ├── App.config
│ ├── CompanyBadWithAllowFieldTypeConversionExceptions.cs
│ ├── IMEX_Tests.cs
│ ├── ConfiguredWorksheetName_SQLStatements_UnitTests.cs
│ ├── WorkSheetNameTests.cs
│ ├── InvalidCastTests.cs
│ ├── LogManagerFactory.cs
│ ├── PersistentConnection_IntegrationTests.cs
│ ├── RowTest.cs
│ ├── CellTest.cs
│ ├── Row_IntegrationTests.cs
│ ├── ConfiguredWorksheetName_IntegrationTests.cs
│ ├── CSV_IntegrationTests.cs
│ ├── NoHeader_SQLStatements_UnitTests.cs
│ ├── LinqToExcel.Tests.csproj
│ ├── IndexToColumnNamesTests.cs
│ ├── CSV_SQLStatements_UnitTests.cs
│ ├── NamedRange_SQLStatements_UnitTests.cs
│ ├── SkipEmptyRows_UnitTests.cs
│ ├── Excel2007_IntegrationTests.cs
│ ├── Range_IntegrationTests.cs
│ ├── NamedRange_IntegrationTests.cs
│ ├── SQLLogStatements_Helper.cs
│ ├── Row_SQLStatement_UnitTests.cs
│ ├── Range_SQLStatements_UnitTests.cs
│ ├── NoHeader_IntregrationTests.cs
│ ├── ColumnMappings_SQLStatements_UnitTests.cs
│ ├── InvalidColumnNamesUsed.cs
│ ├── ColumnMappings_IntegrationTests.cs
│ ├── UnSupportedMethods.cs
│ └── Convention_IntegrationTests.cs
└── LinqToExcel.sln
├── .gitignore
├── License.txt
├── CHANGELOG.md
└── README.md
/.gitattributes:
--------------------------------------------------------------------------------
1 | # correctly commit line endings
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/src/LinqToExcel/LinqToExcel.snk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel/LinqToExcel.snk
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/NoHeader.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/NoHeader.xls
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/Companies.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/Companies.xls
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsb:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsb
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsm:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsm
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/Companies.xlsx
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/EmptyRows.xls:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/EmptyRows.xls
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/NamedRanges.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/NamedRanges.xlsx
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/WorksheetNames.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/paulyoder/LinqToExcel/HEAD/src/LinqToExcel.Tests/ExcelFiles/WorksheetNames.xlsx
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyWithCity.cs:
--------------------------------------------------------------------------------
1 |
2 | namespace LinqToExcel.Tests
3 | {
4 | class CompanyWithCity : Company
5 | {
6 | public string City { get; set; }
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
2 | bin64/
3 | obj/
4 | tests/
5 | *.suo
6 | LinqToExcel.xml
7 | *ReSharper*
8 | *.zip
9 | *.nupkg
10 | src/packages/
11 | *.DotSettings.user
12 | *.csproj.user
13 | .vs/
14 | *.csproj.user
15 | *.DotSettings.user
16 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/Transformations.cs:
--------------------------------------------------------------------------------
1 | namespace LinqToExcel.Tests
2 | {
3 | public class Transformation1
4 | {
5 | public int Value { get; set; }
6 | }
7 |
8 | public class Transformation2
9 | {
10 | public string Value { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Logging/ILogManagerFactory.cs:
--------------------------------------------------------------------------------
1 | // copyright(c) 2016 Stephen Workman (workman.stephen@gmail.com)
2 |
3 | using System;
4 |
5 | namespace LinqToExcel.Logging {
6 | public interface ILogManagerFactory {
7 | ILogProvider GetLogger(Type name);
8 | ILogProvider GetLogger(String name);
9 | }
10 | }
11 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/NoHeader.csv:
--------------------------------------------------------------------------------
1 | ACME2,Bugs Bunny,25,11/11/1918
2 | Word Made Flesh,Chris Heuertz,98,08/08/1994
3 | Anderson University,James Edwards,300,09/01/1917
4 | McDonalds,Ronald McDonald,29839,06/17/1952
5 | The Lemon Drop,George Smorge,5,09/23/1960
6 | Yoder Solutions,Paul Yoder,1,10/09/2008
7 | Ontario Systems,Tony Reisz,4554,08/23/1980
8 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyNullable.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqToExcel.Tests
4 | {
5 | public class CompanyNullable
6 | {
7 | public string Name { get; set; }
8 | public string CEO { get; set; }
9 | public int? EmployeeCount { get; set; }
10 | public DateTime? StartDate { get; set; }
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ExcelFiles/Companies.csv:
--------------------------------------------------------------------------------
1 | Name,CEO,EmployeeCount,StartDate
2 | ACME,Bugs Bunny,25,11/11/1918
3 | Word Made Flesh,Chris Heuertz,98,8/8/1994
4 | Anderson University,James Edwards,300,9/1/1917
5 | McDonalds,Ronald McDonald,29839,6/17/1952
6 | The Lemon Drop,George Smorge,5,9/23/1960
7 | Yoder Solutions,Paul Yoder,1,10/9/2008
8 | Ontario Systems,Tony Reisz,433,8/23/1980
9 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/IContainsUnmappedCells.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 |
3 | namespace LinqToExcel
4 | {
5 | ///
6 | /// Implement this interface to receive values for cells that
7 | /// were not mapped.
8 | ///
9 | public interface IContainsUnmappedCells
10 | {
11 | IDictionary UnmappedCells { get; }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/Company.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqToExcel.Tests
4 | {
5 | public class Company
6 | {
7 | public string Name { get; set; }
8 | public string CEO { get; set; }
9 | public int? EmployeeCount { get; set; }
10 | public DateTime StartDate { get; set; }
11 | public bool IsActive { get; set; }
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/RowNoHeader.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace LinqToExcel
7 | {
8 | public class RowNoHeader : List
9 | {
10 | /// Cells contained within the row
11 | public RowNoHeader(IEnumerable cells)
12 | {
13 | base.AddRange(cells);
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyNameWithUnmappedCells.cs:
--------------------------------------------------------------------------------
1 |
2 | using System.Collections.Generic;
3 |
4 | namespace LinqToExcel.Tests
5 | {
6 | class CompanyNameWithUnmappedCells : IContainsUnmappedCells
7 | {
8 | public CompanyNameWithUnmappedCells()
9 | {
10 | UnmappedCells = new Dictionary();
11 | }
12 |
13 | public string Name { get; set; }
14 | public IDictionary UnmappedCells { get; private set; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Logging/ILogProvider.cs:
--------------------------------------------------------------------------------
1 | // copyright(c) 2016 Stephen Workman (workman.stephen@gmail.com)
2 |
3 | using System;
4 |
5 | namespace LinqToExcel.Logging {
6 | public interface ILogProvider {
7 | bool IsDebugEnabled { get; }
8 | void Debug(Object message);
9 | void DebugFormat(String format, Object arg);
10 | void Error(Object message, Exception exception);
11 | void WarnFormat(String format, Object arg0, Object arg1, Object arg2);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/StrictMappingException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace LinqToExcel.Domain
7 | {
8 | public class StrictMappingException : Exception
9 | {
10 | public StrictMappingException(string message)
11 | : base(message)
12 | { }
13 |
14 | public StrictMappingException(string formatMessage, params object[] args)
15 | : base(string.Format(formatMessage, args))
16 | { }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Attributes/ExcelColumnAttribute.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqToExcel.Attributes
4 | {
5 | [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
6 | public sealed class ExcelColumnAttribute : Attribute
7 | {
8 | private readonly string _columnName;
9 |
10 | public ExcelColumnAttribute(string columnName)
11 | {
12 | _columnName = columnName;
13 | }
14 |
15 | public string ColumnName
16 | {
17 | get { return _columnName; }
18 | }
19 |
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/IAllowFieldTypeConversionExceptions.cs:
--------------------------------------------------------------------------------
1 | using LinqToExcel.Exceptions;
2 | using System.Collections.Generic;
3 |
4 | namespace LinqToExcel
5 | {
6 | ///
7 | /// Implement this interface to bypass the default thrown exception
8 | /// on a field parse error. All exceptions will instead be placed in
9 | /// this list. Be aware that you will still get a typed row back but
10 | /// failed column values should be untrusted.
11 | ///
12 | public interface IAllowFieldTypeConversionExceptions
13 | {
14 | IList FieldTypeConversionExceptions { get; }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyWithColumnAnnotations.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using LinqToExcel.Attributes;
3 |
4 | namespace LinqToExcel.Tests
5 | {
6 | public class CompanyWithColumnAnnotations
7 | {
8 | [ExcelColumn("Company Title")]
9 | public string Name { get; set; }
10 |
11 | [ExcelColumn("Boss")]
12 | public string CEO { get; set; }
13 |
14 | [ExcelColumn("Number of People")]
15 | public int EmployeeCount { get; set; }
16 |
17 | [ExcelColumn("Initiation Date")]
18 | public DateTime StartDate { get; set; }
19 |
20 | [ExcelColumn("Active")]
21 | public string IsActive { get; set; }
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyGoodWithAllowFieldTypeConversionExceptions.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using LinqToExcel.Exceptions;
3 |
4 | namespace LinqToExcel.Tests
5 | {
6 | class CompanyGoodWithAllowFieldTypeConversionExceptions : IAllowFieldTypeConversionExceptions
7 | {
8 | public CompanyGoodWithAllowFieldTypeConversionExceptions()
9 | {
10 | FieldTypeConversionExceptions = new List();
11 | }
12 |
13 | public string Name { get; set; }
14 | public string CEO { get; set; }
15 | public int EmployeeCount { get; set; }
16 |
17 | public IList FieldTypeConversionExceptions { get; private set; }
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/TrimSpacesType.cs:
--------------------------------------------------------------------------------
1 | namespace LinqToExcel.Query
2 | {
3 | ///
4 | /// Indicates how to treat leading and trailing spaces in string values.
5 | ///
6 | public enum TrimSpacesType
7 | {
8 | ///
9 | /// Do not perform any trimming.
10 | ///
11 | None,
12 |
13 | ///
14 | /// Trim leading spaces from strings.
15 | ///
16 | Start,
17 |
18 | ///
19 | /// Trim trailing spaces from strings.
20 | ///
21 | End,
22 |
23 | ///
24 | /// Trim leading and trailing spaces from strings.
25 | ///
26 | Both
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/StrictMappingType.cs:
--------------------------------------------------------------------------------
1 | namespace LinqToExcel.Query
2 | {
3 | ///
4 | /// Class property and worksheet mapping enforcemment type.
5 | ///
6 | public enum StrictMappingType
7 | {
8 | ///
9 | /// All worksheet columns must map to a class property; all class properties must map to a worksheet columm.
10 | ///
11 | Both,
12 |
13 | ///
14 | /// All class properties must map to a worksheet column; other worksheet columns are ignored.
15 | ///
16 | ClassStrict,
17 |
18 | ///
19 | /// No checks are made to enforce worksheet column or class property mappings.
20 | ///
21 | None,
22 |
23 | ///
24 | /// All worksheet columns must map to a class property; other class properties are ignored.
25 | ///
26 | WorksheetStrict
27 | }
28 | }
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/ResultObjectMapping.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using Remotion.Linq.Clauses;
3 |
4 | namespace LinqToExcel.Query
5 | {
6 | public class ResultObjectMapping
7 | {
8 | private readonly Dictionary _resultObjectsBySource = new Dictionary();
9 |
10 | public ResultObjectMapping(IQuerySource querySource, object resultObject)
11 | {
12 | Add(querySource, resultObject);
13 | }
14 |
15 | public void Add(IQuerySource querySource, object resultObject)
16 | {
17 | _resultObjectsBySource.Add(querySource, resultObject);
18 | }
19 |
20 | public T GetObject(IQuerySource source)
21 | {
22 | return (T)_resultObjectsBySource[source];
23 | }
24 |
25 | public IEnumerator> GetEnumerator()
26 | {
27 | return _resultObjectsBySource.GetEnumerator();
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CompanyBadWithAllowFieldTypeConversionExceptions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using LinqToExcel.Exceptions;
4 |
5 | namespace LinqToExcel.Tests
6 | {
7 | class CompanyBadWithAllowFieldTypeConversionExceptions : IAllowFieldTypeConversionExceptions
8 | {
9 | public CompanyBadWithAllowFieldTypeConversionExceptions()
10 | {
11 | FieldTypeConversionExceptions = new List();
12 | }
13 |
14 | public string Name { get; set; }
15 |
16 | ///
17 | /// The CEO column is actually a string and should fail type conversion to int.
18 | ///
19 | public int CEO { get; set; }
20 |
21 | ///
22 | /// The EmployeeCount column is actually a string and should fail type conversion to DateTime.
23 | ///
24 | public DateTime EmployeeCount { get; set; }
25 |
26 | public IList FieldTypeConversionExceptions { get; private set; }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/License.txt:
--------------------------------------------------------------------------------
1 | copyright (c) 2008-2010 Paul Yoder
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
--------------------------------------------------------------------------------
/src/LinqToExcel/License.txt:
--------------------------------------------------------------------------------
1 | copyright (c) 2008-2010 Paul Yoder
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in
11 | all copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
19 | THE SOFTWARE.
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/ExcelQueryConstructorArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Data.OleDb;
4 | using System.Linq;
5 | using System.Text;
6 | using LinqToExcel.Domain;
7 |
8 | namespace LinqToExcel.Query
9 | {
10 | internal class ExcelQueryConstructorArgs
11 | {
12 | internal bool Lazy { get; set; }
13 |
14 | public ExcelQueryConstructorArgs()
15 | {
16 | OleDbServices = OleDbServices.AllServices;
17 | }
18 |
19 | internal string FileName { get; set; }
20 | internal Dictionary ColumnMappings { get; set; }
21 | internal Dictionary> Transformations { get; set; }
22 | internal StrictMappingType? StrictMapping { get; set; }
23 | internal bool UsePersistentConnection { get; set; }
24 | internal TrimSpacesType TrimSpaces { get; set; }
25 | internal bool ReadOnly { get; set; }
26 | internal OleDbServices OleDbServices { get; set; }
27 | internal int CodePageIdentifier { get; set; }
28 | internal bool SkipEmptyRows { get; set; }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/IMEX_Tests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using NUnit.Framework;
4 | using System.IO;
5 |
6 | namespace LinqToExcel.Tests
7 | {
8 | [Author("Paul Yoder", "paulyoder@gmail.com")]
9 | [Category("Integration")]
10 | [TestFixture]
11 | public class IMEX_Tests
12 | {
13 | string _excelFileName;
14 |
15 | [OneTimeSetUp]
16 | public void fs()
17 | {
18 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
19 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
20 | _excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
21 | }
22 |
23 | [Test]
24 | public void date_and_text_column_values_are_not_null()
25 | {
26 | var sheet = new ExcelQueryFactory(new LogManagerFactory());
27 | sheet.FileName = _excelFileName;
28 |
29 | var names = (from x in sheet.Worksheet("IMEX Table")
30 | select x).ToList();
31 |
32 | Assert.AreEqual("Bye", names.Last()["Date"].ToString());
33 | }
34 | }
35 | }
36 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ConfiguredWorksheetName_SQLStatements_UnitTests.cs:
--------------------------------------------------------------------------------
1 | using System.Linq;
2 | using NUnit.Framework;
3 | using System.Data.OleDb;
4 |
5 | namespace LinqToExcel.Tests
6 | {
7 | [Author("Paul Yoder", "paulyoder@gmail.com")]
8 | [Category("Unit")]
9 | [TestFixture]
10 | public class ConfiguredWorksheetName_SQLStatements_UnitTests : SQLLogStatements_Helper
11 | {
12 | [OneTimeSetUp]
13 | public void fs()
14 | {
15 | InstantiateLogger();
16 | }
17 |
18 | [SetUp]
19 | public void Setup()
20 | {
21 | ClearLogEvents();
22 | }
23 |
24 | [Test]
25 | public void table_name_in_sql_statement_matches_configured_table_name()
26 | {
27 | var companies = from c in ExcelQueryFactory.Worksheet("Company Worksheet", "", new LogManagerFactory())
28 | select c;
29 |
30 | try { companies.GetEnumerator(); }
31 | catch (OleDbException) { }
32 | string expectedSql = "SELECT * FROM [Company Worksheet$]";
33 | Assert.AreEqual(expectedSql, GetSQLStatement());
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/WorkSheetNameTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 |
4 | using NUnit.Framework;
5 |
6 | namespace LinqToExcel.Tests {
7 |
8 | [Author("Paul Yoder", "paulyoder@gmail.com")]
9 | [Category("Integration")]
10 | [TestFixture]
11 | public class WorkSheetNameTests {
12 | private String _filesDirectory;
13 |
14 | [OneTimeSetUp]
15 | public void Setup() {
16 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
17 | _filesDirectory = Path.Combine(testDirectory, "ExcelFiles");
18 | }
19 |
20 | [Test]
21 | public void WorkSheetNamesAreDecodedCorrectly() {
22 | var fileName = Path.Combine(_filesDirectory, "WorksheetNames.xlsx");
23 |
24 | var workbook = new ExcelQueryFactory(fileName, new LogManagerFactory());
25 | var worksheetNames = workbook.GetWorksheetNames();
26 |
27 | CollectionAssert.AreEqual(
28 | new [] {
29 | " ' ",
30 | "$woot$",
31 | "Emb$dded",
32 | "Ends with $'\"",
33 | "Ends with a $",
34 | "Has a $ in it"
35 | },
36 | worksheetNames
37 | );
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/InvalidCastTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.IO;
5 | using System.Linq;
6 | using System.Text;
7 |
8 | namespace LinqToExcel.Tests
9 | {
10 | [Author("Alberto Chvaicer", "achvaicer@gmail.com")]
11 | [Category("Integration")]
12 | [TestFixture]
13 | public class InvalidCastTests
14 | {
15 | private IExcelQueryFactory _factory;
16 | private string _excelFileName;
17 |
18 | [OneTimeSetUp]
19 | public void fs()
20 | {
21 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
22 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
23 | _excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
24 |
25 | }
26 |
27 | [SetUp]
28 | public void s()
29 | {
30 | _factory = new ExcelQueryFactory(_excelFileName, new LogManagerFactory());
31 | }
32 |
33 | [Test]
34 | public void invalid_number_cast_with_header()
35 | {
36 | Assert.That(() => (from x in ExcelQueryFactory.Worksheet("Invalid Cast", _excelFileName, new LogManagerFactory())
37 | select x).ToList(), Throws.TypeOf(), "Error on row 8 and column name 'EmployeeCount'.");
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/Cell.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace LinqToExcel
4 | {
5 | ///
6 | /// Represents a cell and its value in an excel spreadsheet
7 | ///
8 | public class Cell
9 | {
10 | ///
11 | /// Cell's value
12 | ///
13 | public object Value { get; private set; }
14 |
15 | /// Cell's value
16 | public Cell(object value)
17 | {
18 | Value = value;
19 | }
20 |
21 | ///
22 | /// Casts the cell's value to the generic argument type
23 | ///
24 | /// Object type to convert to
25 | public T Cast()
26 | {
27 | return (Value == null || Value is DBNull) ?
28 | default(T) :
29 | (T)Convert.ChangeType(Value, typeof(T));
30 | }
31 |
32 | ///
33 | /// Cell's value as a string
34 | ///
35 | public override string ToString()
36 | {
37 | return Value.ToString();
38 | }
39 |
40 | ///
41 | /// Allow cell to be implicitly cast to a string
42 | ///
43 | public static implicit operator string(Cell cell)
44 | {
45 | return cell.ToString();
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/LogManagerFactory.cs:
--------------------------------------------------------------------------------
1 | // copyright(c) 2016 Stephen Workman (workman.stephen@gmail.com)
2 |
3 | using System;
4 |
5 | using log4net;
6 | using LinqToExcel.Logging;
7 |
8 | namespace LinqToExcel.Tests {
9 | public class LogManagerFactory : ILogManagerFactory {
10 | public ILogProvider GetLogger(String name) {
11 | return new LogProvider(LogManager.GetLogger(name));
12 | }
13 |
14 | public ILogProvider GetLogger(Type type) {
15 | return new LogProvider(LogManager.GetLogger(type));
16 | }
17 | }
18 |
19 | public class LogProvider : ILogProvider {
20 | private ILog _iLog;
21 |
22 | public LogProvider(ILog iLog) {
23 | _iLog = iLog;
24 | }
25 |
26 | public Boolean IsDebugEnabled {
27 | get {
28 | if (_iLog != null)
29 | return _iLog.IsDebugEnabled;
30 | return false;
31 | }
32 | }
33 |
34 | public void Debug(Object message) {
35 | if (_iLog != null)
36 | _iLog.Debug(message);
37 | }
38 |
39 | public void DebugFormat(String format, Object arg) {
40 | if (_iLog != null)
41 | _iLog.DebugFormat(format, arg);
42 | }
43 |
44 | public void Error(Object message, Exception exception) {
45 | if (_iLog != null)
46 | _iLog.Error(message, exception);
47 | }
48 |
49 | public void WarnFormat(String format, Object arg0, Object arg1, Object arg2) {
50 | if (_iLog != null)
51 | _iLog.WarnFormat(format, arg0, arg1, arg2);
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/ExcelQueryable.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.Generic;
2 | using System.Linq;
3 | using Remotion.Linq;
4 | using System.Linq.Expressions;
5 | using LinqToExcel.Attributes;
6 | using System;
7 |
8 | using LinqToExcel.Logging;
9 |
10 | using Remotion.Linq.Parsing.Structure;
11 |
12 | namespace LinqToExcel.Query
13 | {
14 | public class ExcelQueryable : QueryableBase
15 | {
16 | private static IQueryExecutor CreateExecutor(ExcelQueryArgs args, ILogManagerFactory logManagerFactory)
17 | {
18 | return new ExcelQueryExecutor(args, logManagerFactory);
19 | }
20 |
21 | // This constructor is called by users, create a new IQueryExecutor.
22 | internal ExcelQueryable(ExcelQueryArgs args, ILogManagerFactory logManagerFactory)
23 | : base( QueryParser.CreateDefault(), CreateExecutor(args, logManagerFactory) )
24 | {
25 | foreach (var property in typeof(T).GetProperties())
26 | {
27 | ExcelColumnAttribute att = (ExcelColumnAttribute)Attribute.GetCustomAttribute(property, typeof(ExcelColumnAttribute));
28 | if (att != null && !args.ColumnMappings.ContainsKey(property.Name))
29 | {
30 | args.ColumnMappings.Add(property.Name, att.ColumnName);
31 | }
32 | }
33 | }
34 |
35 | // This constructor is called indirectly by LINQ's query methods, just pass to base.
36 | public ExcelQueryable(IQueryProvider provider, Expression expression)
37 | : base(provider, expression)
38 | { }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Domain/Row.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using LinqToExcel.Extensions;
4 |
5 | namespace LinqToExcel
6 | {
7 | public class Row : List
8 | {
9 | IDictionary _columnIndexMapping;
10 |
11 | public Row() :
12 | this(new List(),new Dictionary())
13 | { }
14 |
15 | /// Cells contained within the row
16 | /// Column name to cell index mapping
17 | public Row(IList cells, IDictionary columnIndexMapping)
18 | {
19 | for (int i = 0; i < cells.Count; i++)
20 | this.Insert(i, cells[i]);
21 | _columnIndexMapping = columnIndexMapping;
22 | }
23 |
24 | /// Column Name
25 | public Cell this[string columnName]
26 | {
27 | get
28 | {
29 | if (!_columnIndexMapping.ContainsKey(columnName))
30 | throw new ArgumentException(string.Format("'{0}' column name does not exist. Valid column names are '{1}'",
31 | columnName, string.Join("', '", _columnIndexMapping.Keys.ToArray())));
32 | return base[_columnIndexMapping[columnName]];
33 | }
34 | }
35 |
36 | ///
37 | /// List of column names in the row object
38 | ///
39 | public IEnumerable ColumnNames
40 | {
41 | get { return _columnIndexMapping.Keys; }
42 | }
43 | }
44 | }
45 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/SqlParts.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 | using System.Data.OleDb;
5 |
6 | namespace LinqToExcel.Query
7 | {
8 | public class SqlParts
9 | {
10 | public string Aggregate { get; set; }
11 | public string Table { get; set; }
12 | public string Where { get; set; }
13 | public IEnumerable Parameters { get; set; }
14 | public string OrderBy { get; set; }
15 | public bool OrderByAsc { get; set; }
16 | public List ColumnNamesUsed { get; set; }
17 |
18 | public SqlParts()
19 | {
20 | Aggregate = "*";
21 | Parameters = new List();
22 | OrderByAsc = true;
23 | ColumnNamesUsed = new List();
24 | }
25 |
26 | public static implicit operator string(SqlParts sql)
27 | {
28 | return sql.ToString();
29 | }
30 |
31 | public override string ToString()
32 | {
33 | var sql = new StringBuilder();
34 | sql.AppendFormat("SELECT {0} FROM {1}",
35 | Aggregate,
36 | Table);
37 | if (!String.IsNullOrEmpty(Where))
38 | sql.AppendFormat(" WHERE {0}", Where);
39 | if (!String.IsNullOrEmpty(OrderBy))
40 | {
41 | var asc = (OrderByAsc) ? "ASC" : "DESC";
42 | sql.AppendFormat(" ORDER BY [{0}] {1}",
43 | OrderBy,
44 | asc);
45 | }
46 | return sql.ToString();
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/LinqToExcel.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27004.2005
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqToExcel", "LinqToExcel\LinqToExcel.csproj", "{08F80D96-5387-4406-B88B-DCC0CB661702}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LinqToExcel.Tests", "LinqToExcel.Tests\LinqToExcel.Tests.csproj", "{195B956A-8029-44FD-9518-C04F5280611F}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {08F80D96-5387-4406-B88B-DCC0CB661702}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {08F80D96-5387-4406-B88B-DCC0CB661702}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {08F80D96-5387-4406-B88B-DCC0CB661702}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {08F80D96-5387-4406-B88B-DCC0CB661702}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {195B956A-8029-44FD-9518-C04F5280611F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {195B956A-8029-44FD-9518-C04F5280611F}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {195B956A-8029-44FD-9518-C04F5280611F}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {195B956A-8029-44FD-9518-C04F5280611F}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {80264802-F218-4279-85F8-73E6A896B2A7}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/PersistentConnection_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using NUnit.Framework;
5 |
6 | namespace LinqToExcel.Tests
7 | {
8 | [Author("Andrew Corkery", "andrew.corkery@gmail.com")]
9 | [Category("Integration")]
10 | [TestFixture]
11 | public class PersistentConnection_IntegrationTests
12 | {
13 | private IExcelQueryFactory _factory;
14 |
15 | [OneTimeSetUp]
16 | public void fs()
17 | {
18 | string testDirectory = AppDomain.CurrentDomain.BaseDirectory;
19 | string excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
20 | string excelFileName = Path.Combine(excelFilesDirectory, "Companies.xlsm");
21 |
22 | _factory = new ExcelQueryFactory(excelFileName, new LogManagerFactory());
23 | _factory.UsePersistentConnection = true;
24 | }
25 |
26 | [Test]
27 | public void WorksheetRangeNoHeader_returns_7_companies()
28 | {
29 | var companies = from c in _factory.WorksheetRangeNoHeader("A2", "D8", "Sheet1")
30 | select c;
31 |
32 | Assert.AreEqual(7, companies.Count());
33 | }
34 |
35 | [Test]
36 | public void WorksheetRangeNoHeader_can_query_sheet_500_times_on_same_connection()
37 | {
38 | IQueryable rows = null;
39 |
40 | int totalRows = 0;
41 |
42 | for (int i = 0; i < 500; i++)
43 | {
44 | rows = from cm in _factory.WorksheetRangeNoHeader("A2", "D8", "Sheet1")
45 | select cm;
46 |
47 | totalRows += rows.Count();
48 | }
49 |
50 | Assert.AreEqual((500*7), totalRows);
51 | }
52 |
53 | [OneTimeTearDown]
54 | public void td()
55 | {
56 | //dispose of the factory (and persistent connection)
57 | _factory.Dispose();
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Exceptions/ExcelException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace LinqToExcel.Exceptions
7 | {
8 | public class ExcelException : Exception
9 | {
10 | ///
11 | /// Row index where exception occours
12 | ///
13 | public int Row { get; private set; }
14 |
15 | ///
16 | /// Column name where exception occours
17 | ///
18 | public string ColumnName { get; private set; }
19 |
20 | ///
21 | /// Column index where exception occours
22 | ///
23 | public int Column { get; private set; }
24 |
25 | public ExcelException(int row, string columnName, Exception innerException)
26 | : base(string.Format("Error on row {0} and column name '{1}'.", row, columnName), innerException)
27 | {
28 | Row = row;
29 | ColumnName = columnName;
30 | }
31 |
32 | public ExcelException(int row, int column, Exception innerException)
33 | : base(string.Format("Error on row {0} and column '{1}'.", row, Query.ExcelUtilities.ColumnIndexToExcelColumnName(column)), innerException)
34 | {
35 | Row = row;
36 | Column = column;
37 | ColumnName = Query.ExcelUtilities.ColumnIndexToExcelColumnName(column);
38 | }
39 |
40 | public ExcelException(int row, int column, string columnName, Exception innerException)
41 | : base(string.Format("Error on row {0} and column name '{1}'.", row, columnName), innerException)
42 | {
43 | Row = row;
44 | Column = column;
45 | ColumnName = columnName ?? Query.ExcelUtilities.ColumnIndexToExcelColumnName(column);
46 | }
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/RowTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using NUnit.Framework;
4 |
5 | namespace LinqToExcel.Tests
6 | {
7 | [Author("Paul Yoder", "paulyoder@gmail.com")]
8 | [Category("Unit")]
9 | [TestFixture]
10 | public class RowTest
11 | {
12 | IDictionary _columnMappings;
13 | IList _cells;
14 |
15 | [SetUp]
16 | public void s()
17 | {
18 | _columnMappings = new Dictionary();
19 | _columnMappings["Name"] = 0;
20 | _columnMappings["Favorite Sport"] = 1;
21 | _columnMappings["Age"] = 2;
22 |
23 | _cells = new List();
24 | _cells.Add(new Cell("Paul"));
25 | _cells.Add(new Cell("Ultimate Frisbee"));
26 | _cells.Add(new Cell(25));
27 | }
28 |
29 | [Test]
30 | public void index_maps_cells_correctly()
31 | {
32 | var row = new Row(_cells, _columnMappings);
33 | Assert.AreEqual(_cells[0], row[0]);
34 | Assert.AreEqual(_cells[1], row[1]);
35 | Assert.AreEqual(_cells[2], row[2]);
36 | }
37 |
38 | [Test]
39 | public void column_name_index_maps_cells_correctly()
40 | {
41 | var row = new Row(_cells, _columnMappings);
42 | Assert.AreEqual(_cells[0], row["Name"]);
43 | Assert.AreEqual(_cells[1], row["Favorite Sport"]);
44 | Assert.AreEqual(_cells[2], row["Age"]);
45 | }
46 |
47 | [Test]
48 | public void invalid_column_name_index_throws_argument_exception()
49 | {
50 | var newRow = new Row(_cells, _columnMappings);
51 | Assert.That(() => newRow["First Name"],
52 | Throws.TypeOf(), "'First Name' column name does not exist. Valid column names are 'Name', 'Favorite Sport', 'Age'");
53 |
54 | }
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CellTest.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using NUnit.Framework;
3 | namespace LinqToExcel.Tests
4 | {
5 | [Author("Paul Yoder", "paulyoder@gmail.com")]
6 | [Category("Unit")]
7 | [TestFixture]
8 | public class CellTest
9 | {
10 | [Test]
11 | public void Cell_implicitly_converts_to_string()
12 | {
13 | var newCell = new Cell("some value");
14 | Assert.IsTrue("some value" == newCell);
15 | }
16 |
17 | [Test]
18 | public void Constructor_sets_cell_value()
19 | {
20 | var newCell = new Cell("hello");
21 | Assert.AreEqual("hello", newCell.Value);
22 | }
23 |
24 | [Test]
25 | public void As_converts_cell_value_type_to_generic_argument_type()
26 | {
27 | var newCell = new Cell("2");
28 | Assert.AreEqual(2, newCell.Cast());
29 | Assert.AreEqual(typeof(int), newCell.Cast().GetType());
30 | }
31 |
32 | [Test]
33 | public void As_returns_default_generic_value_when_value_is_null()
34 | {
35 | var newCell = new Cell(null);
36 | Assert.AreEqual(0, newCell.Cast());
37 | }
38 |
39 | [Test]
40 | public void ValueAs_returns_default_generic_value_when_value_is_DBNull()
41 | {
42 | var newCell = new Cell(DBNull.Value);
43 | Assert.AreEqual(0, newCell.Cast());
44 | }
45 |
46 | [Test]
47 | public void to_string_returns_value_as_string()
48 | {
49 | var newCell = new Cell("hello");
50 | Assert.AreEqual("hello", newCell.ToString());
51 | }
52 |
53 | [Test]
54 | public void As_throws_exception_when_try_to_convert_invalid_value()
55 | {
56 | var newCell = new Cell("not a number");
57 | Assert.Throws(() => newCell.Cast());
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/Row_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using NUnit.Framework;
4 | using System.IO;
5 |
6 | namespace LinqToExcel.Tests
7 | {
8 | [Author("Paul Yoder", "paulyoder@gmail.com")]
9 | [Category("Integration")]
10 | [TestFixture]
11 | public class Row_IntegrationTests
12 | {
13 | string _excelFileName;
14 | [OneTimeSetUp]
15 | public void fs()
16 | {
17 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
18 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
19 | _excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
20 | }
21 |
22 | [Test]
23 | public void column_values()
24 | {
25 | var firstCompany = (from c in ExcelQueryFactory.Worksheet(null, _excelFileName, null, new LogManagerFactory())
26 | select c).First();
27 |
28 | Assert.AreEqual("ACME", firstCompany["Name"].ToString());
29 | Assert.AreEqual("Bugs Bunny", firstCompany["CEO"].ToString());
30 | Assert.AreEqual(25, firstCompany["EmployeeCount"].Cast());
31 | Assert.AreEqual(new DateTime(1918, 11, 11).Date, firstCompany["StartDate"].Cast().Date);
32 | }
33 |
34 | [Test]
35 | public void columnNames_returns_list_of_column_names()
36 | {
37 | var firstCompany = (from c in ExcelQueryFactory.Worksheet(null, _excelFileName, null, new LogManagerFactory())
38 | select c).First();
39 |
40 | Assert.AreEqual(4, firstCompany.ColumnNames.Count());
41 | Assert.IsTrue(firstCompany.ColumnNames.Contains("Name"));
42 | Assert.IsTrue(firstCompany.ColumnNames.Contains("CEO"));
43 | Assert.IsTrue(firstCompany.ColumnNames.Contains("EmployeeCount"));
44 | Assert.IsTrue(firstCompany.ColumnNames.Contains("StartDate"));
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ### 2.0.0 (PRERELEASE-2)
4 | * Allow connstring suppression of TransactionScope. Thanks **@freakingawesome**.
5 | * Allow lazy queries using yield statements. Thanks **@freakingawesome**.
6 | * Add means to gather exceptions instead of throwing. Thanks **@freakingawesome**.
7 | * Implemented Source Link for easier debugging. Thanks **@MagicAndre1981**.
8 |
9 | ### 2.0.0 (PRERELEASE)
10 |
11 | * Remove support for Microsoft Jet as it was deprecated many years ago, and only works in 32-bit applications.
12 | * MS Ace driver is now a *requirement*.
13 | * Target AnyCPU
14 | * Target .Net Framework v3.5, v4.5.1, and v4.6.
15 | * Fix `ExcelQueryFactory` not being disposed properly.
16 | * Fix incorrect worksheet names that contain a `$`.
17 | * Remotion.Linq updated, and no longer bundled with project.
18 | * Added support for unary expressions in Linq aggregate functions.
19 | * Added support for primitive value type results to be cast to `Nullable` counterparts.
20 | * Fix "item already inserted" issue in AddTransformation. Thanks **@tkestowicz**.
21 | * Throw Exception with row number and column name/number. Thanks **@achvaicer**.
22 | * Added a method of gathering "unmapped cells". Thanks **@freakingawesome**.
23 |
24 | * Other notes:
25 | * Thanks to **@cuongtranba** for helping to move the project to Nunit.
26 |
27 |
28 | ### 1.11.0
29 |
30 | * Refactorings
31 | * Remove dependency on log4net.
32 |
33 | ### 1.10.1
34 |
35 | * Refactorings
36 | * Manually removing log4net.dll from the package lib folder since it's not needed with the NuGet dependency on log4net
37 |
38 | ### 1.10
39 |
40 | * Refactorings
41 | * Added Log4Net as a dependency in the NuGet file
42 |
43 | ### 1.9
44 |
45 | * Enhancements
46 | * Added support for named ranges (by nkilian)
47 |
48 | ### 1.8.1
49 |
50 | * Refactorings
51 | * Referencing Log4Net through its NuGet package
52 |
53 | ### 1.8
54 |
55 | * enhancements
56 | * added **UsePersistentConnection** option to re-use the same connection for multiple queries. (by acorkery)
57 | * added **ReadOnly** option to open the file in readonly mode
58 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/ConfiguredWorksheetName_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using NUnit.Framework;
4 | using System.IO;
5 | using System.Data;
6 |
7 | namespace LinqToExcel.Tests
8 | {
9 | [Author("Paul Yoder", "paulyoder@gmail.com")]
10 | [Category("Integration")]
11 | [TestFixture]
12 | public class ConfiguredWorksheetName_IntegrationTests : SQLLogStatements_Helper
13 | {
14 | private string _excelFileName;
15 |
16 | [OneTimeSetUp]
17 | public void fs()
18 | {
19 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
20 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
21 | _excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
22 | InstantiateLogger();
23 | }
24 |
25 | [SetUp]
26 | public void s()
27 | {
28 | ClearLogEvents();
29 | }
30 |
31 | [Test]
32 | public void data_is_read_from_correct_worksheet()
33 | {
34 | var companies = from c in ExcelQueryFactory.Worksheet("More Companies", _excelFileName, new LogManagerFactory())
35 | select c;
36 |
37 | Assert.AreEqual(3, companies.ToList().Count);
38 | }
39 |
40 | [Test]
41 | public void worksheetIndex_of_2_uses_third_table_name_orderedby_name()
42 | {
43 | var companies = (from c in ExcelQueryFactory.Worksheet(3, _excelFileName, new LogManagerFactory())
44 | select c).ToList();
45 |
46 | var expectedSql = "SELECT * FROM [More Companies$]";
47 | Assert.AreEqual(expectedSql, GetSQLStatement(), "SQL Statement");
48 | }
49 |
50 | [Test]
51 | public void worksheetIndex_too_high_throws_exception()
52 | {
53 | Assert.That(() => from c in ExcelQueryFactory.Worksheet(100, _excelFileName, new LogManagerFactory())
54 | select c,
55 | Throws.TypeOf());
56 | }
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/LinqToExcel/LinqToExcel.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net35;net451;net46
5 | 2.0.0.2
6 | 2.0.0.0
7 | 2.0.0-PRERELEASE-2
8 | Yoder Web Solutions, LLC
9 | Paul Yoder, Stephen Workman
10 | Easily retrieve data from spreadsheets and csv files by using LINQ
11 | Copyright © Paul Yoder 2019
12 | https://github.com/paulyoder/LinqToExcel/blob/master/License.txt
13 | https://github.com/paulyoder/LinqToExcel
14 | Linq Excel spreadsheet csv
15 | en-US
16 | true
17 | true
18 | false
19 | LinqToExcel.snk
20 | https://github.com/paulyoder/LinqToExcel
21 |
22 | true
23 |
24 |
25 | true
26 |
27 |
28 | $(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 | Always
39 |
40 |
41 |
42 |
43 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CSV_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using NUnit.Framework;
4 | using System.IO;
5 |
6 | namespace LinqToExcel.Tests
7 | {
8 | [Author("Paul Yoder", "paulyoder@gmail.com")]
9 | [Category("Integration")]
10 | [TestFixture]
11 | public class CSV_IntegrationTests
12 | {
13 | string _fileName;
14 |
15 | [OneTimeSetUp]
16 | public void fs()
17 | {
18 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
19 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
20 | _fileName = Path.Combine(excelFilesDirectory, "Companies.csv");
21 | }
22 |
23 | [Test]
24 | public void select_all()
25 | {
26 | var companies = from c in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
27 | select c;
28 |
29 | Assert.AreEqual(7, companies.ToList().Count);
30 | }
31 |
32 | [Test]
33 | public void where_contains_string_criteria()
34 | {
35 | var companies = from c in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
36 | where c.Name == "ACME"
37 | select c;
38 |
39 | Assert.AreEqual(1, companies.ToList().Count);
40 | }
41 |
42 | [Test]
43 | public void where_contains_int_criteria()
44 | {
45 | var companies = from c in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
46 | where c.EmployeeCount > 20
47 | select c;
48 |
49 | Assert.AreEqual(5, companies.ToList().Count);
50 | }
51 |
52 | [Test]
53 | public void where_contains_datetime_criteria()
54 | {
55 | var companies = from c in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
56 | where c.StartDate == new DateTime(1980, 8, 23)
57 | select c;
58 |
59 | Assert.AreEqual(1, companies.ToList().Count);
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/NoHeader_SQLStatements_UnitTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NUnit.Framework;
6 | using System.Data.OleDb;
7 |
8 | namespace LinqToExcel.Tests
9 | {
10 | [Author("Paul Yoder", "paulyoder@gmail.com")]
11 | [Category("Unit")]
12 | [TestFixture]
13 | public class NoHeader_SQLStatements_UnitTests : SQLLogStatements_Helper
14 | {
15 | private ExcelQueryFactory _factory;
16 |
17 | [OneTimeSetUp]
18 | public void fs()
19 | {
20 | InstantiateLogger();
21 | }
22 |
23 | [SetUp]
24 | public void s()
25 | {
26 | _factory = new ExcelQueryFactory("", new LogManagerFactory());
27 | ClearLogEvents();
28 | }
29 |
30 | [Test]
31 | public void range_csv_file_throws_exception()
32 | {
33 | var csvFile = @"C:\ExcelFiles\NoHeaderRange.csv";
34 |
35 | var excel = new ExcelQueryFactory(csvFile, new LogManagerFactory());
36 | Assert.That(() => (from c in excel.WorksheetRangeNoHeader("B9", "E15")
37 | select c),
38 | Throws.TypeOf(), "Cannot use WorksheetRangeNoHeader on csv files");
39 |
40 | }
41 |
42 | [Test]
43 | public void where_clause()
44 | {
45 | var warnerCompany = from c in _factory.WorksheetNoHeader()
46 | where c[1] == "Bugs Bunny"
47 | select c;
48 |
49 | try { warnerCompany.GetEnumerator(); }
50 | catch (OleDbException) { }
51 |
52 | var expectedSQL = "SELECT * FROM [Sheet1$] WHERE (F2 = ?)";
53 | Assert.AreEqual(expectedSQL, GetSQLStatement());
54 | }
55 |
56 | [Test]
57 | public void where_is_null()
58 | {
59 | var warnerCompany = from c in _factory.WorksheetNoHeader()
60 | where c[1] == null
61 | select c;
62 |
63 | try { warnerCompany.GetEnumerator(); }
64 | catch (OleDbException) { }
65 |
66 | var expectedSQL = "SELECT * FROM [Sheet1$] WHERE (F2 IS NULL)";
67 | Assert.AreEqual(expectedSQL, GetSQLStatement());
68 | }
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/OleDbServices.cs:
--------------------------------------------------------------------------------
1 | namespace LinqToExcel.Query
2 | {
3 | ///
4 | /// Describes which services the OLE DB connection will use.
5 | ///
6 | ///
7 | /// This allows you to change the OLE DB Services value in the connection string, which among other
8 | /// features, will allow you to opt out of implicit transactions (e.g. those created using
9 | /// TransactionScope).
10 | ///
11 | ///
12 | /// Services enabled | Value in connection string
13 | /// ============================================================================
14 | /// All services (the default) | "OLE DB Services = -1;"
15 | /// All services except pooling | "OLE DB Services = -2;"
16 | /// All services except pooling and auto-enlistment | "OLE DB Services = -4;"
17 | /// All services except client cursor | "OLE DB Services = -5;"
18 | /// All services except client cursor and pooling | "OLE DB Services = -6;"
19 | /// No services | "OLE DB Services = 0;"
20 | ///
21 | ///
22 | /// See https://msdn.microsoft.com/en-us/library/ms810829.aspx for more information.
23 | ///
24 | public enum OleDbServices
25 | {
26 | ///
27 | /// This is the default value for OLE DB Services in connection strings where it
28 | /// is not explicitly specified. Sets OLE DB Services to -1 in the connection string.
29 | ///
30 | AllServices = -1,
31 |
32 | ///
33 | /// Sets OLE DB Services to -2 in the connection string.
34 | ///
35 | AllServicesExceptPooling = -2,
36 |
37 | ///
38 | /// This will disable auto-enlistment in TransactionScope.
39 | /// Sets OLE DB Services to -4 in the connection string.
40 | ///
41 | AllServicesExceptPoolingAndAutoEnlistment = -4,
42 |
43 | ///
44 | /// Sets OLE DB Services to -5 in the connection string.
45 | ///
46 | AllServicesExceptClientCursor = -5,
47 |
48 | ///
49 | /// Sets OLE DB Services to -6 in the connection string.
50 | ///
51 | AllServicesExceptClientCursorAndPooling = -6,
52 |
53 | ///
54 | /// Sets OLE DB Services to 0 in the connection string.
55 | ///
56 | NoServices = 0,
57 | }
58 | }
59 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/LinqToExcel.Tests.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | net35;net451;net46
5 | Full
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | x64
20 | false
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 | Always
30 |
31 |
32 | Always
33 |
34 |
35 | Always
36 |
37 |
38 | Always
39 |
40 |
41 | Always
42 |
43 |
44 | Always
45 |
46 |
47 | Always
48 |
49 |
50 | Always
51 |
52 |
53 | Always
54 |
55 |
56 |
57 | Always
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/IndexToColumnNamesTests.cs:
--------------------------------------------------------------------------------
1 | using NUnit.Framework;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 |
7 | namespace LinqToExcel.Tests
8 | {
9 | [TestFixture]
10 | [Category("Unit")]
11 | [Author("Alberto Chvaicer")]
12 | public class IndexToColumnNamesTests
13 | {
14 | [Test]
15 | public void valid_excel_column_indexes()
16 | {
17 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(1), "A");
18 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(2), "B");
19 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(3), "C");
20 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(25), "Y");
21 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(26), "Z");
22 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(27), "AA");
23 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(28), "AB");
24 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(51), "AY");
25 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(52), "AZ");
26 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(53), "BA");
27 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(54), "BB");
28 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(701), "ZY");
29 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(702), "ZZ");
30 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(703), "AAA");
31 | Assert.AreEqual(LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(704), "AAB");
32 | }
33 |
34 | [Test]
35 | public void negative_integer_should_throw_exception()
36 | {
37 | Assert.That(() => LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(-1), Throws.ArgumentException, "Index should be a positive integer");
38 | }
39 |
40 | [Test]
41 | public void zero_should_throw_exception()
42 | {
43 | Assert.That(() => LinqToExcel.Query.ExcelUtilities.ColumnIndexToExcelColumnName(-1), Throws.ArgumentException, "Index should be a positive integer");
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/CSV_SQLStatements_UnitTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using NUnit.Framework;
4 | using System.IO;
5 | using System.Data;
6 |
7 | namespace LinqToExcel.Tests
8 | {
9 | [Author("Paul Yoder", "paulyoder@gmail.com")]
10 | [Category("Unit")]
11 | [TestFixture]
12 | public class CSV_SQLStatements_UnitTests : SQLLogStatements_Helper
13 | {
14 | string _fileName;
15 |
16 | [OneTimeSetUp]
17 | public void fs()
18 | {
19 | _fileName = Path.Combine(Path.GetTempPath(), "spreadsheet.csv");
20 | InstantiateLogger();
21 | }
22 |
23 | [SetUp]
24 | public void s()
25 | {
26 | ClearLogEvents();
27 | }
28 |
29 | [Test]
30 | public void Connection_string_data_source_is_directory_of_csv_file()
31 | {
32 | var people = from p in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
33 | select p;
34 |
35 | try { people.GetEnumerator(); }
36 | catch (DataException) { }
37 |
38 | var dataSource = GetDataSource();
39 | Assert.AreEqual(Path.GetDirectoryName(_fileName), dataSource);
40 | }
41 |
42 | [Test]
43 | public void Connection_string_extended_properties_have_csv_settings()
44 | {
45 | var people = from p in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
46 | select p;
47 |
48 | try { people.GetEnumerator(); }
49 | catch (DataException) { }
50 |
51 | var extendedProperties = GetExtendedProperties();
52 |
53 | Assert.AreEqual("\"text;Excel 12.0;HDR=YES;IMEX=1\"", extendedProperties);
54 |
55 | }
56 |
57 | [Test]
58 | public void Table_name_is_csv_file_name()
59 | {
60 | var people = from p in ExcelQueryFactory.Worksheet(null, _fileName, null, new LogManagerFactory())
61 | select p;
62 |
63 | try { people.GetEnumerator(); }
64 | catch (DataException) { }
65 |
66 | var tableName = GetTableName(GetSQLStatement());
67 | Assert.AreEqual(Path.GetFileName(_fileName), tableName);
68 | }
69 |
70 | private string GetTableName(string sqlStatement)
71 | {
72 | var words = sqlStatement.Split(" ".ToCharArray());
73 | for (var i = 0; i < words.Length; i++)
74 | {
75 | if (words[i] == "FROM")
76 | return words[i + 1]
77 | .Replace("[", "")
78 | .Replace("]", "");
79 | }
80 | return "";
81 | }
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Query/ProjectorBuildingExpressionTreeVisitor.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Reflection;
3 | using System.Linq.Expressions;
4 | using Remotion.Linq.Clauses.Expressions;
5 | using Remotion.Linq.Parsing;
6 |
7 | namespace LinqToExcel.Query
8 | {
9 | public class ProjectorBuildingExpressionTreeVisitor : RelinqExpressionVisitor
10 | {
11 | // This is the generic ResultObjectMapping.GetObject() method we'll use to obtain a queried object for an IQuerySource.
12 | private static readonly MethodInfo s_getObjectGenericMethodDefinition = typeof(ResultObjectMapping).GetMethod("GetObject");
13 |
14 | // Call this method to get the projector. T is the type of the result (after the projection).
15 | public static Func BuildProjector(Expression selectExpression)
16 | {
17 | // This is the parameter of the delegat we're building. It's the ResultObjectMapping, which holds all the input data needed for the projection.
18 | var resultItemParameter = Expression.Parameter(typeof(ResultObjectMapping), "resultItem");
19 |
20 | // The visitor gives us the projector's body. It simply replaces all QuerySourceReferenceExpressions with calls to ResultObjectMapping.GetObject().
21 | var visitor = new ProjectorBuildingExpressionTreeVisitor(resultItemParameter);
22 | var body = visitor.Visit(selectExpression);
23 |
24 | // Construct a LambdaExpression from parameter and body and compile it into a delegate.
25 | var projector = Expression.Lambda>(body, resultItemParameter);
26 | return projector.Compile();
27 | }
28 |
29 | private readonly ParameterExpression _resultItemParameter;
30 |
31 | private ProjectorBuildingExpressionTreeVisitor(ParameterExpression resultItemParameter)
32 | {
33 | _resultItemParameter = resultItemParameter;
34 | }
35 |
36 | protected override Expression VisitQuerySourceReference(QuerySourceReferenceExpression expression)
37 | {
38 | // Substitute generic parameter "T" of ResultObjectMapping.GetObject() with type of query source item, then return a call to that method
39 | // with the query source referenced by the expression.
40 | var getObjectMethod = s_getObjectGenericMethodDefinition.MakeGenericMethod(expression.Type);
41 | return Expression.Call(_resultItemParameter, getObjectMethod, Expression.Constant(expression.ReferencedQuerySource));
42 | }
43 |
44 | protected override Expression VisitSubQuery(SubQueryExpression expression)
45 | {
46 | throw new NotSupportedException("This provider does not support subqueries in the select projection.");
47 | }
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/NamedRange_SQLStatements_UnitTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NUnit.Framework;
6 | using System.Data.OleDb;
7 |
8 | namespace LinqToExcel.Tests
9 | {
10 | [Author("Paul Yoder", "paulyoder@gmail.com")]
11 | [Category("Unit")]
12 | [TestFixture]
13 | public class NamedRange_SQLStatements_UnitTests : SQLLogStatements_Helper
14 | {
15 | private IExcelQueryFactory _factory;
16 |
17 | [OneTimeSetUp]
18 | public void fs()
19 | {
20 | InstantiateLogger();
21 | }
22 |
23 | [SetUp]
24 | public void s()
25 | {
26 | ClearLogEvents();
27 | _factory = new ExcelQueryFactory("", new LogManagerFactory());
28 | }
29 |
30 | [Test]
31 | public void Appends_named_range_info_to_table_name()
32 | {
33 | var companies = from c in _factory.NamedRange("Sheet1", "NamedRange")
34 | select c;
35 |
36 | try { companies.GetEnumerator(); }
37 | catch (OleDbException) { }
38 | Assert.AreEqual("SELECT * FROM [Sheet1$NamedRange]", GetSQLStatement());
39 | }
40 |
41 | [Test]
42 | public void use_sheetData_method()
43 | {
44 | var companies = from c in _factory.NamedRange("Sheet1", "NamedRange")
45 | select c;
46 |
47 | try { companies.GetEnumerator(); }
48 | catch (OleDbException) { }
49 | Assert.AreEqual("SELECT * FROM [Sheet1$NamedRange]", GetSQLStatement());
50 | }
51 |
52 | [Test]
53 | public void use_row_where_is_null()
54 | {
55 | var companies = from c in _factory.NamedRange("Sheet1", "NamedRange")
56 | where c["City"] == null
57 | select c;
58 | //System.Diagnostics.Debugger.Launch();
59 | try { companies.GetEnumerator(); }
60 | catch (OleDbException) { }
61 | var expectedSql = string.Format("SELECT * FROM [Sheet1$NamedRange] WHERE ({0} IS NULL)", GetSQLFieldName("City"));
62 | Assert.AreEqual(expectedSql, GetSQLStatement());
63 | }
64 |
65 | [Test]
66 | public void use_sheetData_where_is_null()
67 | {
68 | var companies = from c in _factory.NamedRange("worksheetName", "NamedRange")
69 | where c.Name == null
70 | select c;
71 |
72 | try { companies.GetEnumerator(); }
73 | catch (OleDbException) { }
74 | var expectedSql = string.Format("SELECT * FROM [worksheetName$NamedRange] WHERE ({0} IS NULL)", GetSQLFieldName("Name"));
75 | Assert.AreEqual(expectedSql, GetSQLStatement());
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/SkipEmptyRows_UnitTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Linq;
4 | using NUnit.Framework;
5 |
6 | namespace LinqToExcel.Tests
7 | {
8 | [Category("Unit")]
9 | [TestFixture]
10 | public class SkipEmptyRows_UnitTests
11 | {
12 | ExcelQueryFactory _factory;
13 | string _fileName;
14 |
15 | [OneTimeSetUp]
16 | public void fs()
17 | {
18 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
19 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
20 | _fileName = Path.Combine(excelFilesDirectory, "EmptyRows.xls");
21 | }
22 |
23 | [SetUp]
24 | public void s()
25 | {
26 | _factory = new ExcelQueryFactory(_fileName, new LogManagerFactory());
27 | }
28 |
29 | [Test]
30 | public void CanGetAllRows_GetTypeResults()
31 | {
32 | _factory.SkipEmptyRows = false;
33 | var skippedRows = from row in _factory.Worksheet("EmptyRows")
34 | select row;
35 |
36 | Assert.AreEqual(6, skippedRows.ToList().Count);
37 | }
38 |
39 | [Test]
40 | public void CanGetAllRows_GetRowResults()
41 | {
42 | _factory.SkipEmptyRows = false;
43 | var skippedRows = from row in _factory.Worksheet("EmptyRows")
44 | select row;
45 |
46 | Assert.AreEqual(6, skippedRows.ToList().Count);
47 | }
48 |
49 | [Test]
50 | public void CanGetAllRows_GetRowNoHeaderResults()
51 | {
52 | _factory.SkipEmptyRows = false;
53 | var skippedRows = from row in _factory.WorksheetNoHeader("EmptyRowsNoHeader")
54 | select row;
55 |
56 | Assert.AreEqual(6, skippedRows.ToList().Count);
57 | }
58 |
59 | [Test]
60 | public void CanSkipEmptyRows_GetTypeResults()
61 | {
62 | _factory.SkipEmptyRows = true;
63 | var skippedRows = from row in _factory.Worksheet("EmptyRows")
64 | select row;
65 |
66 | Assert.AreEqual(3, skippedRows.ToList().Count);
67 | }
68 |
69 | [Test]
70 | public void CanSkipEmptyRows_GetRowResults()
71 | {
72 | _factory.SkipEmptyRows = true;
73 | var skippedRows = from row in _factory.Worksheet("EmptyRows")
74 | select row;
75 |
76 | Assert.AreEqual(3, skippedRows.ToList().Count);
77 | }
78 |
79 | [Test]
80 | public void CanSkipEmptyRows_GetRowNoHeaderResults()
81 | {
82 | _factory.SkipEmptyRows = true;
83 | var skippedRows = from row in _factory.WorksheetNoHeader("EmptyRowsNoHeader")
84 | select row;
85 |
86 | Assert.AreEqual(3, skippedRows.ToList().Count);
87 | }
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/Excel2007_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Linq;
3 | using LinqToExcel.Domain;
4 | using NUnit.Framework;
5 | using System.IO;
6 |
7 | namespace LinqToExcel.Tests
8 | {
9 | [Author("Paul Yoder", "paulyoder@gmail.com")]
10 | [Category("Integration")]
11 | [TestFixture]
12 | public class Excel2007_IntegrationTests
13 | {
14 | string _filesDirectory;
15 |
16 | [OneTimeSetUp]
17 | public void fs()
18 | {
19 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
20 | _filesDirectory = Path.Combine(testDirectory, "ExcelFiles");
21 | }
22 |
23 | [Test]
24 | public void xlsx()
25 | {
26 | var fileName = Path.Combine(_filesDirectory, "Companies.xlsx");
27 | var companies = from c in ExcelQueryFactory.Worksheet("MoreCompanies", fileName, new LogManagerFactory())
28 | select c;
29 |
30 | //Using ToList() because using Count() first would change the sql
31 | //string to "SELECT COUNT(*)" which we're not testing here
32 | Assert.AreEqual(3, companies.ToList().Count);
33 | }
34 |
35 | [Test]
36 | public void xlsm()
37 | {
38 | var fileName = Path.Combine(_filesDirectory, "Companies.xlsm");
39 | var companies = from c in ExcelQueryFactory.Worksheet("MoreCompanies", fileName, null, new LogManagerFactory())
40 | select c;
41 |
42 | //Using ToList() because using Count() first would change the sql
43 | //string to "SELECT COUNT(*)" which we're not testing here
44 | Assert.AreEqual(3, companies.ToList().Count);
45 | }
46 |
47 | [Test]
48 | public void xlsb()
49 | {
50 | var fileName = Path.Combine(_filesDirectory, "Companies.xlsb");
51 | var companies = from c in ExcelQueryFactory.Worksheet(null, fileName, null, new LogManagerFactory())
52 | select c;
53 |
54 | //Using ToList() because using Count() first would change the sql
55 | //string to "SELECT COUNT(*)" which we're not testing here
56 | Assert.AreEqual(7, companies.ToList().Count);
57 | }
58 |
59 | [Test]
60 | public void xls_with_Ace_DatabaseEngine()
61 | {
62 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
63 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
64 | var excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
65 |
66 | var excel = new ExcelQueryFactory(excelFileName, new LogManagerFactory());
67 | var companies = from c in excel.Worksheet()
68 | select c;
69 |
70 | Assert.AreEqual(7, companies.ToList().Count);
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/src/LinqToExcel.Tests/Range_IntegrationTests.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using NUnit.Framework;
6 | using System.IO;
7 |
8 | namespace LinqToExcel.Tests
9 | {
10 | [Author("Paul Yoder", "paulyoder@gmail.com")]
11 | [Category("Integration")]
12 | [TestFixture]
13 | public class Range_IntegrationTests
14 | {
15 | ExcelQueryFactory _factory;
16 | string _excelFileName;
17 |
18 | [OneTimeSetUp]
19 | public void fs()
20 | {
21 | var testDirectory = AppDomain.CurrentDomain.BaseDirectory;
22 | var excelFilesDirectory = Path.Combine(testDirectory, "ExcelFiles");
23 | _excelFileName = Path.Combine(excelFilesDirectory, "Companies.xls");
24 | }
25 |
26 | [SetUp]
27 | public void s()
28 | {
29 | _factory = new ExcelQueryFactory(_excelFileName, new LogManagerFactory());
30 | }
31 |
32 | [Test]
33 | public void use_sheetData_and_worksheetIndex()
34 | {
35 | var companies = from c in _factory.WorksheetRange("C6", "F13", 5)
36 | select c;
37 |
38 | Assert.AreEqual(7, companies.Count(), "Count");
39 | Assert.AreEqual("ACME", companies.First().Name, "First Company Name");
40 | }
41 |
42 | [Test]
43 | public void use_row_and_worksheetIndex()
44 | {
45 | var companies = from c in _factory.WorksheetRange("c6", "f13", 5)
46 | select c;
47 |
48 | Assert.AreEqual(7, companies.Count(), "Count");
49 | Assert.AreEqual("Ontario Systems", companies.Last()["Name"].ToString(), "Last Company Name");
50 | }
51 |
52 |
53 | [Test]
54 | public void use_sheetData_where_null()
55 | {
56 | var factory = new ExcelQueryFactory(_excelFileName + "x", new LogManagerFactory());
57 | var companies = from c in factory.WorksheetRange("A1", "D4", "NullCells")
58 | where c.EmployeeCount == null
59 | select c;
60 |
61 | Assert.AreEqual(2, companies.Count(), "Count");
62 | }
63 |
64 | [Test]
65 | public void use_row_where_null()
66 | {
67 | var factory = new ExcelQueryFactory(_excelFileName + "x", new LogManagerFactory());
68 | var companies = from c in factory.WorksheetRange("A1", "D4", "NullCells")
69 | where c["EmployeeCount"] == null
70 | select c;
71 |
72 | Assert.AreEqual(2, companies.Count(), "Count");
73 | }
74 |
75 | [Test]
76 | public void use_row_no_header_where_null()
77 | {
78 | var factory = new ExcelQueryFactory(_excelFileName + "x", new LogManagerFactory());
79 | var companies = from c in factory.WorksheetRangeNoHeader("A1", "D4", "NullCells")
80 | where c[2] == null
81 | select c;
82 |
83 | Assert.AreEqual(2, companies.Count(), "Count");
84 | }
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/LinqToExcel/Extensions/CommonExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Reflection;
4 | using System.Collections;
5 | using System.Text.RegularExpressions;
6 | using System.Linq.Expressions;
7 |
8 | namespace LinqToExcel.Extensions
9 | {
10 | public static class CommonExtensions
11 | {
12 | ///
13 | /// Sets the value of a property
14 | ///
15 | /// Name of the property
16 | /// Value to set the property to
17 | public static void SetProperty(this object @object, string propertyName, object value)
18 | {
19 | @object.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, @object, new object[] { value });
20 | }
21 |
22 | ///
23 | /// Calls a method
24 | ///
25 | /// Name of the method
26 | /// Method arguments
27 | /// Return value of the method
28 | public static object CallMethod(this object @object, string methodName, params object[] args)
29 | {
30 | return @object.GetType().InvokeMember(methodName, BindingFlags.InvokeMethod, null, @object, args);
31 | }
32 |
33 | public static T Cast(this object @object)
34 | {
35 | return (T)@object.Cast(typeof(T));
36 | }
37 |
38 | public static object Cast(this object @object, Type castType)
39 | {
40 | //return null for DBNull values
41 | if (@object == null || @object.GetType() == typeof(DBNull) || @object.ToString() == "null")
42 | return null;
43 |
44 | //checking for nullable types
45 | if (castType.IsGenericType &&
46 | castType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
47 | {
48 | castType = Nullable.GetUnderlyingType(castType);
49 | }
50 | return Convert.ChangeType(@object, castType);
51 | }
52 |
53 | public static IEnumerable Cast(this IEnumerable | | | | | | |