How to read a csv file and show it on a Visualforce page?

How to read a csv file and show it on a Visualforce page?

Sample Code:


Visualforce Page:

<apex:page controller=”Sample”>
<apex:form >
    <apex:pageBlock id=”pg”>
        <apex:pageBlockButtons location=”bottom”>
            <apex:commandButton value=”Show” action=”{!show}”/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >File<apex:inputFile value=”{!fileForExport}”/></apex:pageBlockSectionItem>
        </apex:pageBlockSection>
    </apex:pageBlock>
   
    <apex:pageBlock rendered=”{!showBool}”>
        <apex:pageBlockTable value=”{!listOutput}” var=”o”>  
            <apex:repeat value=”{!o}” var=”i”>
                <apex:column value=”{!i}”/>
            </apex:repeat>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:form>
</apex:page>

Apex Class:

public class Sample {
    public Blob fileForExport {get;set;}
    public Boolean showBool {get;set;}
    public String output {get;set;}
    public List<List<String>> listOutput {get;set;}


    public Sample() {
        showBool = false;
        listOutput = new List<List<String>>();        
    }
    
    public void show() {
        showBool = true;
        output = fileForExport.toString();
        List<String> tempList = new List<String>();
        tempList = output.split(‘n’);
        for(String str : tempList) {
            listOutput.add(str.split(‘,’));
        }
    }
}

Output:

Cheers!!!

Leave a Reply