Importing a CSV file using Apex and Visualforce

Here is an example of importing a CSV file using Apex and Visualforce. Depending on your requirements, you may need to enhance this solution with additional error handling, validation, and business logic.


Visualforce Page-

<apex:page controller="demoImportDataFromCSV">


    <apex:form >

        <apex:pagemessages />

        <apex:pageBlock >

            <apex:pageBlockSection columns="2"> 

                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>

                  <apex:commandButton value="Import Product" action="{!importCSVFile}"/>

            </apex:pageBlockSection>

        </apex:pageBlock>

        <apex:pageBlock >

           <apex:pageblocktable value="{!prodList}" var="prod">

              <apex:column value="{! prod.name}" />

              <apex:column value="{! prod. StockKeepingUnit}" />

              <apex:column value="{! prod.IsActive}" />

        </apex:pageblocktable>

     </apex:pageBlock>

   </apex:form>

</apex:page>`


Controller-

public class demoImportDataFromCSV {

public Blob csvFileBody{get;set;}

public string csvAsString{get;set;}

public String[] csvFileLines{get;set;}

public List<Product2> prodList{get;set;}

  public demoImportDataFromCSV(){

    csvFileLines = new String[]{};

    prodList = New List< Product2 >(); 

  }

  

  public void importCSVFile(){

       try{

           csvAsString = csvFileBody.toString();

           csvFileLines = csvAsString.split('\n'); 

           for(Integer i=1;i<csvFileLines.size();i++){

               Product2 prodObj = new Product2() ;

               string[] csvRecordData = csvFileLines[i].split(',');

               prodObj.name = csvRecordData[0] ;             

               prodObj.StockKeepingUnit = csvRecordData[1];

               prodObj.IsActive = csvRecordData[2];

               prodList.add(prodObj);   

           }

          Insert prodList;

        }

        catch (Exception ex)

        {

            ApexPages.Message errorMessage = new     ApexPages.Message(ApexPages.severity.ERROR,'Error occurred while importing data.');

            ApexPages.addMessage(errorMessage);

        }  

  }

}


Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach