Import .csv file using Apex (and VF)
VF Page:
<apex:page controller="importRecords">
<apex:form >
<apex:pagemessages />
<apex:pageBlock >
<apex:pageBlockSection columns="4">
<apex:inputFile value="{!csvFBody}" filename="{!csvString}"/>
<apex:commandButton value="Import" action="{!importCSVF}"/>
</apex:pageBlockSection>
</apex:pageBlock>
<apex:pageBlock >
<apex:pageblocktable value="{!aList}" var="a">
<apex:column value="{!a.Name}" />
<apex:column value="{!a.AccountNumber}" />
<apex:column value="{!a.Type}" />
<apex:column value="{!a.Accountsource}" />
<apex:column value="{!a.Industry }" />
</apex:pageblocktable>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Class:
public class importRecords {
public Blob csvFBody{get;set;}
public string csvString{get;set;}
public String[] csvF{get;set;}
public List<Account> aList{get;set;}
public importRecords(){
csvF = new String[]{};
aList = New List<Account>();
}
public void importCSVF(){
try{
csvString = csvFBody.toString();
csvF = csvString.split('\n');
for(Integer i=1;i<csvF.size();i++){
Account a = new Account() ;
string[] csvRecordData = csvF[i].split(',');
a.name = csvRecordData[0] ;
a.accountnumber = csvRecordData[1];
a.Type = csvRecordData[2];
a.AccountSource = csvRecordData[3];
a.Industry = csvRecordData[4];
aList.add(a);
}
insert aList;
}
catch (Exception e)
{
ApexPages.Message errMsg = new ApexPages.Message(ApexPages.severity.ERROR,'Error');
ApexPages.addMessage(errMsg);
}
}
}
Output:
On wrong file –
hello, from what i experienced with this code
ReplyDeletehow do we create a csv for this code? i tried from excel-->save as csv, it always said error on csv.
This is regarding import .csv file
ReplyDelete