Insert CSV file into a object
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection >
<apex:outputText >Select The File</apex:outputText>
<apex:inputFile value="{!body}" />
</apex:pageBlockSection>
<apex:commandButton value="Save" action="{!importingCSVFile}" />
</apex:pageBlock>
</apex:form>
</apex:page>
public class HWCSVFileRead {
public string stringVal {set;get;}
public string[] liststring {set;get;}
public Blob body {set;get;}
public list<medical__c> medical {set;get;}
public list<medical__c> medical1 {set;get;}
public list<medical__c> medical2 {set;get;}
public Inserting_Record__c inst {set;get;}
public HWCSVFileRead(ApexPages.StandardController controller){
liststring=new string[]{};
medical=new list<medical__c>();
medical2=new list<medical__c>();
inst=(Inserting_Record__c)controller.getRecord();
}
public void importingCSVFile(){
set<string> names=new set<string>();
medical1=[select id, Name, Availability__c, Cost_per_Unit__c, Expire_Date__c from medical__c];
for(medical__c md:medical1){
names.add(md.name);
}
stringVal=body.toString();
liststring=stringVal.split('\n');
for(integer i=0; i<liststring.size(); i++){
medical__c med=new medical__c();
string[] csvFields=liststring[i].split(',');
med.Name =csvFields[0];
med.Availability__c =integer.valueof(csvFields[1]);
med.Cost_per_Unit__c =decimal.valueOf(csvFields[2]);
string dates=csvFields[3].trim();
string[] dmy=dates.split('/');
integer mm=integer.valueof(dmy[0]);
integer dd=integer.valueof(dmy[1]);
integer yy=integer.valueof(dmy[2]);
med.Expire_Date__c=date.newInstance(yy, mm, dd);
medical.add(med);
}
for(medical__c mdc:medical){
medical__c mdcl=new medical__c();
mdcl.name=mdc.Name;
mdcl.Availability__c= mdc.Availability__c;
mdcl.Cost_per_Unit__c = mdc.Cost_per_Unit__c;
mdcl.Expire_Date__c=mdc.Expire_Date__c;
medical2.add(mdcl);
}
upsert medical2;
}
}
Thanks for sharing an information to us.
ReplyDeleteSalesforce Online Training