Visualforce Page

Upload Data Through CSV File in Visualforce Page | Salesforce Developer Guide

You might have a requirement where you need to upload a csv file in your custom object.

In this blog, we’ll see how to upload the data in a custom object using .csv file. First, create a visualforce page and paste the following code. 

Advertisement

Here, I have used the custom object Project__c, It would show the input field for the project name and have the input for file upload and the command button to save the file.

<apex:page controller="RegisterandSaveCSVFileClass">
    <apex:form >
        <apex:pageBlock >
            <apex:messages />
            <apex:pageBlockSection columns="2" showHeader="true" title="Project Details" >
                <apex:inputField value="{!newProject.Name}"/>
            </apex:pageBlockSection>
            <apex:pageBlockSection >
                <apex:inputfile value="{!attachment.body}" filename="{!attachment.Name}" />
                <apex:commandbutton value="Upload and save" action="{!saveButtonAction}"/>
            </apex:pageBlockSection> 
        </apex:pageBlock> 
    </apex:form>
</apex:page>

dont miss out iconDon't forget to check out: Future Methods in Apex | The Salesforce Developer Guide

Now, open preview and check, it would show the input field for the name and upload button to save the file.

Create a new apex class and you will there create validation, that if the file is of type .csv only, then it will save that file otherwise, it would through an error.

Apex Class

First, you should check whether the uploading file is in proper .csv format or not, and then save the attachment.

public class RegisterandSaveCSVFileClass {    
    public Project__c newProject {get; set;}
    public Attachment attachment {get;set;}    
    public RegisterandSaveCSVFileClass(){
        newProject = new Project__c();
        attachment = new Attachment();
    }
    public void saveButtonAction(){
        System.debug('newProject.Name'+newProject.Name);
        if(newProject.Name != null){
            insert newProject;               
            if(attachment.Name.endsWith('.csv')){
                attachment.parentid = newProject.id;
                insert attachment;                
            }else{
                ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'You need to upload only CSV document');
                ApexPages.addMessage(myMsg); 
                return ;
            }
        }
    }    
}

dont miss out iconCheck out another amazing blog by Krati here: Set Up GIT in Visual Studio Code in macOS | Salesforce Developer Guide

Responses

Popular Salesforce Blogs