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
Anu-SFDCAnu-SFDC 

Parsing CSV with Column Names

Hi

 

I want to parse the csv file with column names..

 

Here is my code.

 

public class Test_ReadExcel_Cls{

public string nameFile{get;set;}
string[] filelines=new String[]{};
public Blob contentFile{get;set;}

public Test_ReadExcel_Cls(){}

public Pagereference ReadFile(){

nameFile=contentFile.toString();
 filelines = nameFile.split('\n');

for(Integer i=1;i<filelines.size();i++)
   {
         String[] inputvalues = new String[]{};
            inputvalues = filelines[i].split(',');
   }
return null;
}
}

 

 

Here i am calling the values with integers like inputvalues[0], inputvalues[1] etc...

 

But I need to call them with Column names.. like name, address etc..

 

How can I?

 

Plz suggest me

 

AnnyAnny

Hi ,

 

Please find the below code .It will read the 2 csv files with columns and it will gnerate final csv.Hope it will works to u.

 

import java.io.File;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import au.com.bytecode.opencsv.CSVReader;


public class CSVReaderAndGenerator {
static final String GROUPID="GroupId" ;
static final String GROUP_VALUE_ID="00G80000001L1P8EAK" ;  
  
  public static void main(String args[]) {
  try
  {
   FileOutputStream csvfilestream= new FileOutputStream(args[1]);
   System.out.println("Arg[0]  "+args[0]);
   String Inputfile =  args[0];
   
   CSVReader InputfileReader = new CSVReader(new FileReader(Inputfile));
   String[] InputfileRecoder;
   String salesRepcols[] = InputfileReader.readNext();//reads the header line
   
   StringBuilder csvfileString= new StringBuilder();
   int numofsalesrepcols = salesRepcols.length;
   
   for (int i = 0; i < numofsalesrepcols; i++) {
    csvfileString.append(salesRepcols[i]).append(",");

   }
   csvfileString.append(GROUPID).append("\n");
        
   while ((InputfileRecoder = InputfileReader.readNext()) != null) {
    
    for (int i = 0; i < InputfileRecoder.length; i++) {
     String InputString=InputfileRecoder[i];
     csvfileString.append(InputString).append(",");   
     } 
    
   csvfileString.append(GROUP_VALUE_ID).append(","); 
   csvfileString.append("\n");
   }
   if(csvfileString.length()>0 ){
   csvfileString.deleteCharAt(csvfileString.length()-1);
   }else{
    
    System.out.println("******* Extract File didn't Find any Match With Input File Or The File is Empty");
   } 
   
   System.out.println("csvfileString=="+csvfileString);
   csvfilestream.write(csvfileString.toString().getBytes());
   csvfilestream.flush();
   csvfilestream.close(); 
  
  }
  catch(FileNotFoundException fe)
  {
   System.out.println("ERROR: " + fe.getMessage());
  }
  catch (Exception e) {
   e.printStackTrace();
  }
 }
}