Tag Archives: CSV

Data Import From CSV Using Visualforce Page

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 with sharing 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(){
        csvAsString = csvFileBody.toString();
        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>

Output:

CSV Helper

Biswajeet   March 25, 2014   No Comments on CSV Helper

A .NET library for reading and writing CSV files. Extremely fast, flexible and easy to use. Supports reading and writing of custom class objects.

The first thing to do is to Install CsvHelper.
To install CsvHelper, run the following from the Package Manager Console.

Install-Package CsvHelper 

Now add CsvHelper to the program by adding:

using CsvHelper;

The next step is to create a class which has properties with the same name of the column headings found in the csv file.  Below you will find an example of a class which does this:

public class Customer
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNo { get; set; }
    public string Country { get; set; }
} 

Finally create an instance of CSVReader and invoke the GetRecords method using the DataRecord class. Below you will find an example of this:

using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using CsvHelper;
namespace CSVHelperReadSample
{
    internal class Program
    {
       private static void Main(string[] args)
       {
          using (var sr = new StreamReader(@"Customerlist.csv"))
          {
             var reader = new CsvReader(sr);

             //CSVReader will now read the whole file into an enumerable
             IEnumerable<datarecord> records = reader.GetRecords<customer>();

             //First 5 records in CSV file will be printed to the Output Window
             foreach (DataRecord record in records.Take(5))
             {
                 Debug.Print("{0} {1}, {2}, {3}", record.Name, record.Address, record.PhoneNo, record.Country);
             }
         }
      }
   }
}