Sometimes we need to read a CSV file in a Visualforce Page. Here is an example to read a CSV file and display it in Visualforce Page. Below example reads a CSV file having Account records in it and displays them in a table.
CSV file format used in this example:
Controller:
Public class Sample { public Blob csvFileBody {get;set;} Public string csvAsString {get;set;} Public String[] csvFileLines {get;set;} Public String[] inputValues {get;set;} Public List<string> fieldList {get;set;} Public List<account> sObjectList {get;set;} public Sample(){ csvFileLines = new String[]{}; fieldList = New List<string>(); sObjectList = New List<sObject>(); } Public void readcsvFile(){ String hexResult = EncodingUtil.convertToHex(csvFileBody); final Integer bytesCount = hexResult.length() >> 1; String[] bytes = new String[bytesCount]; for(Integer i = 0; i < bytesCount; ++i){ bytes[i] = hexResult.mid(i << 1, 2); } csvAsString = EncodingUtil.urlDecode('%' + String.join(bytes, '%'), 'ISO-8859-1'); csvFileLines = csvAsString.split('\n'); inputValues = new String[]{}; for(string st:csvfilelines[0].split(',')){ fieldList.add(st); } for(Integer i=1; i<csvfilelines.size(); i++){ Account accRec = new Account() ; string[] csvRecordData = csvFileLines[i].split(','); accRec.Name = csvRecordData[0] ; accRec.AccountNumber = csvRecordData[1]; accRec.Type = csvRecordData[2]; accRec.Industry = csvRecordData[3]; sObjectList.add(accRec); } } }
Visualforce Page:
<apex:page controller="Sample"> <apex:form> <apex:pageBlock> <apex:panelGrid columns="2"> <apex:inputFile value="{!csvFileBody}" filename="{!csvAsString}"/> <apex:commandButton value="Read CSV" action="{!readcsvFile}"/> </apex:panelGrid> </apex:pageBlock> <apex:pageBlock> <apex:pageblocktable value="{!sObjectList}" var="rec"> <apex:column value="{!rec.Name}" /> <apex:column value="{!rec.AccountNumber}"/> <apex:column value="{!rec.Type}" /> <apex:column value="{!rec.Industry}" /> </apex:pageblocktable> </apex:pageBlock> </apex:form> </apex:page>