Blog, Development, Howto

How to generate Excel Template from code

2 years ago as a part of Dynamics CRM 2016 release Microsoft introduced “Word/Excel Document Templates”. I saw examples how to generate Word template but have never seen the same example for Excel. Here is what I found after several hours spent with DB of CRM and ILSpy:

var request = new OrganizationRequest("RenderTemplateFromView");
request["Template"] = new EntityReference("documenttemplate", new Guid("ECF388DE-1033-4C7C-93F3-0803B16C09C7"));
request["View"] = new EntityReference("savedquery", new Guid("00000000-0000-0000-00AA-000010003001"));

var response = service.Execute(request);

var fileContent = (byte[]) response["ExcelFile"];

//Do whatever you need with file content - I saved it to hard drive
File.WriteAllBytes("GeneratedExcel.xlsx", fileContent);

Huge limitation of this code – it can’t be ran from Sandboxed plugins/custom workflow activity so if you want to use it from Sandboxed code – you will have to look for a workaround.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.