Tuesday 2 July 2019

Export using Code Programitically MSCRM

 var exportToExcelRequest = new OrganizationRequest("ExportToExcel");
                exportToExcelRequest.Parameters = new ParameterCollection();
                //Has to be a savedquery aka "System View" or userquery aka "Saved View"
                //The view has to exist, otherwise will error out
                //Guid of the view has to be passed
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("View",
                    new EntityReference("savedquery", new Guid(ConfigurationManager.AppSettings["SavedViewId"]))));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("FetchXml", @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                          <entity name='entity name'>
                   ' descending='false' />
                            <filter type='and'>
                              <condition attribute='statecode' operator='eq' value='0' />
                            </filter>
                        </entity>
                    </fetch>"));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("LayoutXml", @"
                    <grid name='resultset' object='2' jump='lvo_name' select='1' icon='1' preview='1'>
                        <row name='result' id='primary key'>
                        </row>
                    </grid>"));
                //need these params to keep org service happy
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryApi", ""));
                exportToExcelRequest.Parameters.Add(new KeyValuePair<string, object>("QueryParameters",
                    new InputArgumentCollection()));
                var exportToExcelResponse = organizationService.Execute(exportToExcelRequest);
                if (exportToExcelResponse.Results.Any())
                {
                    File.WriteAllBytes(filePath, exportToExcelResponse.Results["ExcelFile"] as byte[]);
                }

1 comment: