Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

multiple primitive types in a variable array raises System.ArgumentException: 'Object of type 'x' cannot be converted to type 'y' #100

Closed
Paul-Fatovich opened this issue Aug 15, 2019 · 2 comments
Milestone

Comments

@Paul-Fatovich
Copy link

Great library, however I am having an issue when mixing types in an array when using AddVariable.
For example:


const string outputFile = @"out.xlsx";

			var template = new XLTemplate(@"template.xlsx");
			var strings = new[] {
				"string",
				"1" ,
				"string",
				};

			var mixed = new[] {
				(object) "string",
				(object) 1 ,
				(object) "string",
				};

			
			template.AddVariable("strings", strings);
			template.AddVariable("mixed", mixed);
			template.Generate();

The mixed array will generate a System.ArgumentException: 'Object of type 'System.Int32' cannot be converted to type 'System.String' when the template is generated.

I looked through the source and the issue is in FormulaEvaluator.cs the constructor for the internal Parameter it is setting an expected type: i.e Expression.Parameter(value.GetType(), name)
however by changing it to ParameterExpression = Expression.Parameter(typeof(object), name);
the error no longer occurs.

The reason converting all values to strings is undesirable is, the generated excel file shows a warning: the number in the cell is formatted as text or preceded by a apostrophe.
This also causes a side effect that any number formatting on that cell will be ignored (like currency)

@Paul-Fatovich
Copy link
Author

Did some further testing and looks like simply using typeof(object) does not work if it is a dynamic object because then lambda.DynamicInvoke(pars.Select(p => p.Value).ToArray()); fails in EvalNoCache with InvalidOperationException: Target object is not an ExpandoObject.

So would suggest checking if the value is simple type first and only then using typeof(object)

@b0bi79 b0bi79 added this to the 0.2.2 milestone Jul 9, 2021
@b0bi79
Copy link
Member

b0bi79 commented Jul 9, 2021

Fixed with #207

@b0bi79 b0bi79 closed this as completed Jul 9, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants