Exporting Records to a CSV file using the classic COM ASP API.

3 minute read time.

A customer had the requirement to allow users to export opportunity information to a file that could be opened in Excel.

I have provided below some example code that is designed to be called from a Button Group associated with the System Action OpportunityList. When the page runs it will create a CSV file containing all the records current in context.

I used the CRM.FindRecord method to create a Record object as I wanted to make sure that the export followed the security rights for the user. The user should not access data that do not have rights to see. In the code below I have also retrieved the data from the same view that the OpportunityList System Action uses. I did this because the export should include Company and Person information and not just raw data from the opportunity table.

The code will create the csv file in either the company library folder or the shared library folder depending on the context in which the page is invoked. A record will be created in the Library table and the user's screen will be redirected to either the company or person documents tab or the shared documents tab in the My CRM menu depending on context.

When the page runs it creates the exported file and adds a library record so that it can be access from the interface.

The file can then be downloaded and access in Excel.

The code can be changed as you need.

[code language="javascript"]

var iDominantKey = Number(Request.Querystring("Key0"));

//This variable will hold the folder path for the company and person library
var strLibraryPath = "";
//This variable will hold the Action Code used for the redirect once the file has been created.
var iLibraryActionCode;
//This variable will hold the context
var strContext ="";

//Define Library Record with basic settings
var recLibrary = CRM.CreateRecord("library");
recLibrary.libr_userid= CRM.GetContextInfo("user","user_userid");
recLibrary.libr_channelid= CRM.GetContextInfo("user","user_primarychannelid");
recLibrary.libr_type= "TargetListExport";
recLibrary.libr_active = 'Y';

//set the WhereClause and library information depending on context.
switch (iDominantKey)
{
case 1:
strContext="Company ";
Arg = "oppo_primarycompanyid=" + CRM.GetContextInfo("company","comp_companyid");
strLibraryPath = CRM.GetContextInfo("company","comp_librarydir");
//Add Details to library record
recLibrary.libr_companyid= CRM.GetContextInfo("company","comp_companyid");
recLibrary.libr_personid= CRM.GetContextInfo("person","pers_personid");
recLibrary.libr_filepath= strLibraryPath;
recLibrary.libr_category= "Sales";
recLibrary.libr_global= "N";

iLibraryActionCode=340;
break;
case 2:
strContext="Person ";
Arg = "oppo_primarypersonid=" + CRM.GetContextInfo("person","pers_personid");
strLibraryPath = CRM.GetContextInfo("person","pers_librarydir");
recLibrary.libr_companyid= CRM.GetContextInfo("company","comp_companyid");
recLibrary.libr_personid= CRM.GetContextInfo("person","pers_personid");
recLibrary.libr_filepath= strLibraryPath;
recLibrary.libr_category= "Sales";
recLibrary.libr_global= "N";

iLibraryActionCode=340;
break;
case 4:
//User Context
strContext="User ";
Arg = "oppo_assigneduserid=" + CRM.GetContextInfo("user","user_userid");
recLibrary.libr_filepath= strLibraryPath;
recLibrary.libr_category= "MyCRM";
recLibrary.libr_global= "Y";
recLibrary.Libr_Mergetemplate = 'N';

iLibraryActionCode=1575;
break;
case 5:
//Team Context
strContext="Team ";
Arg = "oppo_channelid=" + CRM.GetContextInfo("user","user_primarychannelid");
recLibrary.libr_filepath= strLibraryPath;
recLibrary.libr_category= "MyCRM";
recLibrary.libr_global= "Y";
recLibrary.Libr_Mergetemplate = 'N';

iLibraryActionCode=1575
break;
default:
strContext="User ";
Arg = "oppo_assigneduserid=" + CRM.GetContextInfo("user","user_userid");
recLibrary.libr_filepath= strLibraryPath;
recLibrary.libr_category= "MyCRM";
recLibrary.libr_global= "Y";
recLibrary.Libr_Mergetemplate = 'N';

iLibraryActionCode=1575

}

//Retrieve opportunity information using the view vListOpportunity
var recOpportunity = CRM.FindRecord("opportunity,vListOpportunity",Arg);

//Retrieve Document Store path from custom_sysparams table.
var custom_sysparams = CRM.FindRecord('custom_sysparams',"parm_name='DocStore'");

//Build full library folder path
var strFolderPath =custom_sysparams.parm_value+strLibraryPath;

//Prepare to create document using date and context information
var myDate = new Date();
var strDate= String(myDate.getFullYear())+String(myDate.getMonth())+String(myDate.getDate())+String(myDate.getHours())+String(myDate.getMinutes());
var strDocumentName = strContext+"Opportunity List"+strDate+".csv";

//Instantiate the FileSystemObject
var ForReading = 1, ForWriting = 2, ForAppending = 8;
var TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0;
var mySystemObject = new ActiveXObject("Scripting.FileSystemObject");

try
{
//Create the library folder
var libraryFolder = mySystemObject.CreateFolder(strFolderPath);
}
catch(e)
{
//folder already exists
}

//Create the csv file and access the file for writing
mySystemObject.CreateTextFile(strFolderPath+"\\"+strDocumentName, true);
var myFile = mySystemObject.GetFile(strFolderPath+"\\"+strDocumentName);

var myFileTextStream = myFile.OpenAsTextStream(ForAppending, TristateUseDefault);
var strOutPut
//Process the rows of the retrieved opportunity data set
while (!recOpportunity.eof)
{
strOutPut = recOpportunity.oppo_status;
strOutPut +=','+recOpportunity.oppo_description;
//wrap fields with double quotes that may contain commas
strOutPut +=','+'"'+recOpportunity.comp_name+'"';
strOutPut +=','+'"'+recOpportunity.pers_fullname+'"';
strOutPut +=','+recOpportunity.oppo_opened;
strOutPut +=','+recOpportunity.oppo_stage;
strOutPut +=','+recOpportunity.oppo_priority;
strOutPut +=','+recOpportunity.oppo_secterr;
myFileTextStream.WriteLine(strOutPut);
recOpportunity.NextRecord();
}

myFileTextStream.Close();

/////////////////////////

//complete library record and save...
recLibrary.libr_filename= strDocumentName;
recLibrary.libr_note= "Opportunity List export";
recLibrary.libr_status = "Final";
recLibrary.SaveChanges();

//Redirect to the library
Response.Redirect(CRM.URL(iLibraryActionCode));
[/code]