function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Priya MishraPriya Mishra 

csv file upload in the custom object with all the validations via vf page

Hi All,

This is very urgent help.

I Have to insert the record from the visualforce page from a csv file  to the custom object called call_log and check all the valid calidations like if csv file is empty or not having the valid columns and after upload if any error is there need to export the error in the excel file. how to do this please help me witht the sample apex logic for this requirement.

Regards,
Priya Mishra
RituSharmaRituSharma
It would be difficult to provide specific details until we know more detailed requirements. But I am sure that below URL will help you to kickstart the work:

https://jayakrishnasfdc.wordpress.com/2018/09/29/import-csv-file-data-using-apex-vf-page/
 
ANUTEJANUTEJ (Salesforce Developers) 
Hi Priya,

I found the below example in this link (https://www.sfdcpoint.com/salesforce/import-csv-file-using-apex-visualforce/#:~:text=Now%20we%20need%20to%20write,be%20inserted%20on%20account%20records.)  wherein they are uploading account details you can use a similar example for the custom object as well.
 
<apex:page controller="importDataFromCSVController">
    <apex:form >
        <apex:pagemessages />
        <apex:pageBlock >
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Import Account" action="{!importCSVFile}"/>
            </apex:pageBlockSection>
        </apex:pageBlock>
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
              <apex:column value="{!acc.name}" />
              <apex:column value="{!acc.AccountNumber}" />
              <apex:column value="{!acc.Type}" />
              <apex:column value="{!acc.Accountsource}" />
              <apex:column value="{!acc.Industry }" />
        </apex:pageblocktable>
     </apex:pageBlock>
   </apex:form>
</apex:page>
 
public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<account> acclist{get;set;}
  public importDataFromCSVController(){
    csvFileLines = new String[]{};
    acclist = New List<Account>(); 
  }
  
  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               Account accObj = new Account() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               accObj.name = csvRecordData[0] ;             
               accObj.accountnumber = csvRecordData[1];
               accObj.Type = csvRecordData[2];
               accObj.AccountSource = csvRecordData[3];   
               accObj.Industry = csvRecordData[4];                                                                             
               acclist.add(accObj);   
           }
        //insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.ERROR,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}
Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
 
Priya MishraPriya Mishra
Thanks ANUTEJ,

The code workes for some conditions only actully when inserting the date and time field while parsing the csv it is not parsing this field showing error in the apex class while value mapping.

 accObj.Paid_Date__c= csvRecordData[5];
here error showes for parsing.
1. After inserting the record in the object the records are showing the vf page itself i dont want this to show here. only success msg should show.
2. second thing is the object has 2 diffrent record type i need to insert the record to the specific record type in that object how can we add for the record type in the code.

3. When csv file is empty error is not showing need to validate the file has the headers or not.
4. If suppose with the above code if csv file has diffrent headers in the it is inserting the record in the wrong field.

Please suggest me for the above. it seems urgent requirement.


please find my code.

visualforce page:

<apex:page controller="importDataFromCSVController" showHeader="false">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0;" />
 <apex:includeScript value="{!URLFOR($Resource.Jquery_Core_Plugin, 'jquery-1.9.1.min.js')}" />
 
<!--<script type="text/javascript">
function validateFileType()
    {
        var isValid=false;
        var filename= $('.fileSelector').val();
        if(filename!=undefined && filename!='')
            {
                 var ext = filename.split('.').pop().toLowerCase();
                if(ext=='csv')
                    {
                       isValid=true; 
                    }
                
            }
        if(isValid==false)
            {
                alert('Please save the file as csv and upload.');
            }
       
        return isValid;
    }
      
      </script>  
 
 -->
 

<style>
.custom1  {
    background-color:#337ab7;
     
    }
     .errorM3{
    color: :#7a7a7a!important;
    border:0px;
    border-top: 1px solid #e5e5e5;
    position: relative;
    padding: 30px;
    background-color: #ffe8e8;
  font-family: OpenSans-Light,verdana;
    font-size: 14px;
    border-radius:0px!important;
           display : block;

  
</style>





 <c:FormHeader >  </c:FormHeader>

    <apex:form >
    
     <div class="content-wrapper">       
                <div class="TOD-UI" id="main-content">
                    <div class="custom1">
                     <div id="upload_wrapper" style="margin-top: 75px;">
                     
                     </div>
        <apex:pagemessages />
        <apex:pageBlock > 
        
        <header class="Title">
        <apex:pageBlock title="Nominations" >
        <p style="padding: 20px; line-height: 1.5em; padding-left: 0px;">
             
             <font color="black">
              1.  Use "Mass Upload Followup".<br/>
              2.  Upload 250 rows or less at a time. Make sure your data is valid.<br/>
              3.  Save your file in .csv (CSV Delimited) format and Upload.<br/>
              </font> </p>
        </apex:pageBlock> 
            <apex:pageBlockSection columns="4"> 
                  <apex:inputFile value="{!csvFileBody}"  filename="{!csvAsString}"/>
                  <apex:commandButton value="Upload" action="{!importCSVFile}" onclick="return validateFileType();" style="width:110px;height:27px;border-radius:7px;  color: #141414;background-color: #f2faf7;border: 1px solid #00a1de;"  styleClass="btn-grey"/>
            </apex:pageBlockSection>
       </header>
      
       
        </apex:pageBlock>  </div>
       </div>
       </div> 
        <apex:pageBlock >
           <apex:pageblocktable value="{!accList}" var="acc">
          <apex:column value="{!acc.First_Name__c}" />
              <apex:column value="{!acc.Email__c}" />
              <apex:column value="{!acc.EIN__c}" />
              <apex:column value="{!acc.Last_Name__c}" />
              <apex:column value="{!acc.City__c}" />
              
              <apex:column value="{!acc.Phone_number__c}" />
              <apex:column value="{!acc.CellPhone__c}" />
              <apex:column value="{!acc.SA_Name__c}" />
           
        </apex:pageblocktable>
    </apex:pageBlock>
 
   </apex:form>  
</apex:page>


--------------------------------------------------------------------------------


controller:


======================


public class importDataFromCSVController {
public Blob csvFileBody{get;set;}
public string csvAsString{get;set;}
public String[] csvFileLines{get;set;}
public List<Call_Log__c> acclist{get;set;}
public string upload_err_msg{get; set;}

  public importDataFromCSVController(){
   upload_err_msg='';
    csvFileLines = new String[]{};
    acclist = New List<Call_Log__c>(); 
  }
 
  
  public void importCSVFile(){
       try{
           csvAsString = csvFileBody.toString();
           csvFileLines = csvAsString.split('\n'); 
            
           for(Integer i=1;i<csvFileLines.size();i++){
               Call_Log__c accObj = new Call_Log__c() ;
               string[] csvRecordData = csvFileLines[i].split(',');
               accObj.First_Name__c= csvRecordData[0] ;             
               accObj.Email__c= csvRecordData[1];
               accObj.EIN__c= csvRecordData[2];
               accObj.Last_Name__c= csvRecordData[3];   
               accObj.City__c= csvRecordData[4];  
               accObj.Phone_number__c= csvRecordData[5];
               accObj.CellPhone__c= csvRecordData[6];
               accObj.SA_Name__c= csvRecordData[7];                                                                           
               acclist.add(accObj);   
           }
        insert acclist;
        }
        catch (Exception e)
        {
            ApexPages.Message errorMessage = new ApexPages.Message(ApexPages.severity.INFO,'An error has occured while importin data Please make sure input csv file is correct');
            ApexPages.addMessage(errorMessage);
        }  
  }
}

thanks in advance.