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
Amit Singh1989Amit Singh1989 

Display CSV in visualforce page

Hi friend,

i have created an visualforce page where i have used <apex:inputFile /> to take any CSV file as input

then i am displaying that CSV file's data into the same vf page in tabular format...

 

but i want that selected CSV's data should be displayed in another vf page. (so by setting attribute renderas="pdf" i can view CSV's data in a PDF format)

 

 

how can i do this?

 

 

here is my code...

 

<apex:page controller="uploadCSVcontroller">
  <apex:form >
  <apex:pageMessages id="pm"/>
  <apex:inputFile value="{!contentFile}" filename="{!nameFile}"/>
  <apex:commandButton value="Display" id="theButton"/>  
  
  
  
  <apex:pageBlock >
  <apex:outputPanel id="results">
  <p>nameFile: {!nameFile}</p>
  <p>rowCount: {!rowCount}</p>
  <p>colCount: {!colCount}</p>
    <table title="CSV Output" border="1" width="100%">
       <apex:repeat value="{!results}" var="row">
           <tr>
               <apex:repeat value="{!row}" var="cell">
                   <td> {!cell} </td>
               </apex:repeat>
           </tr>
       </apex:repeat>
     </table>
  </apex:outputPanel>
  </apex:pageBlock>
  </apex:form>
</apex:page>







Controller


public class uploadCSVcontroller 
  {

    public Blob contentFile { get; set; }
    public String nameFile { get; set; }
    public Integer rowCount { get; set; }
    public Integer colCount { get; set; }
    
    public List<List<String>> getResults() 
    {
        List<List<String>> parsedCSV = new List<List<String>>();
        rowCount = 0;
        colCount = 0;
        if (contentFile != null)
        {
            String fileString = contentFile.toString();
            parsedCSV = parseCSV(fileString, False);
            rowCount = parsedCSV.size();
            for (List<String> row : parsedCSV)
            {
                if (row.size() > colCount)
                {
                    colCount = row.size();
                }
            }
        }
        return parsedCSV;
    }
    
    public Pagereference CreatePDF()
     {
      pagereference pr = new pagereference('/apex/FinalReport1');
      pr.setredirect(true);
      return pr;
     }
    
    public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) 
     {
        List<List<String>> allFields = new List<List<String>>();
        contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
        contents = contents.replaceAll('""','DBLQT');
        List<String> lines = new List<String>();
        try 
        {
          lines = contents.split('\r'); // using carriage return accomodates windows, unix, and mac files
        }
        catch (System.ListException e) 
        {
            System.debug('Limits exceeded?' + e.getMessage());
        }
        Integer num = 0;
        for(String line: lines) 
        {
           if (line.replaceAll(',','').trim().length() == 0) break;
            List<String> fields = line.split(',');  
            List<String> cleanFields = new List<String>();
            String compositeField;
            Boolean makeCompositeField = false;
            for(String field: fields) 
            {
                if (field.startsWith('"') && field.endsWith('"')) 
                {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
                else if (field.startsWith('"')) 
                {
                    makeCompositeField = true;
                    compositeField = field;
                }
                else if (field.endsWith('"')) 
                {
                    compositeField += ',' + field;
                    cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                    makeCompositeField = false;
                }
                else if (makeCompositeField) 
                {
                    compositeField +=  ',' + field;
                }
                else
                {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
            }
            
            allFields.add(cleanFields);
        }
        if (skipHeaders) allFields.remove(0);
        return allFields;       
     }

}

 

 

 

Thanks,

Amit Singh

Best Answer chosen by Admin (Salesforce Developers) 
abivenkatabivenkat

 

hi amit singh1989,

 

Better read the CSV file and store in the document object in first VF page. give a button as "View and Convert to PDF" in the first VF Page. 

 

When clicking the button, just redirect them to the second VF page and just show the content of the CSV page by querying the file from the Document object and put "RenderAs" attribute in that page itself.

 

What i think is, upload the file and show the content in the first page itself and provide a button as "Convert to PDF". while clicking the button, u just redirect to the second page. in that second page controller class, retrieve the same CSV file and convert to PDF by adding the "RenderAs" attribute in the second page. 

 

Accept as solution if u find this post is useful for you..

 

Thanks,

abivenkat.

 

 

All Answers

Chamil MadusankaChamil Madusanka

Refer this example

 

http://www.forcetree.com/2010/08/read-and-insert-records-from-csv-file.html

 

If a reply to a post answers your question or resolves your problem, please mark it as the solution to the post so that others may benefit.

Amit Singh1989Amit Singh1989

chamil, link given by you also dealing with the one vf page only.

 

i want to select csv file in one vf page and display its content tinto another vf page.

 

 

Thanks,

Amit

abivenkatabivenkat

 

hi amit singh1989,

 

Better read the CSV file and store in the document object in first VF page. give a button as "View and Convert to PDF" in the first VF Page. 

 

When clicking the button, just redirect them to the second VF page and just show the content of the CSV page by querying the file from the Document object and put "RenderAs" attribute in that page itself.

 

What i think is, upload the file and show the content in the first page itself and provide a button as "Convert to PDF". while clicking the button, u just redirect to the second page. in that second page controller class, retrieve the same CSV file and convert to PDF by adding the "RenderAs" attribute in the second page. 

 

Accept as solution if u find this post is useful for you..

 

Thanks,

abivenkat.

 

 

This was selected as the best answer
Amit Singh1989Amit Singh1989

Thank you abivenkat ,

 

it works fine for a simple cls fine,

in my case,first i want to create a summary report in csv format then want to save it into Document (as you suggested using visualforce page),the once i want to view pdf i am getting such kind of ERROR.

 

BLOB is not a valid UTF-8 string

 

here is my code,

 

<apex:form >
<apex:pageMessages id="pm"/>
 
  <apex:pageBlock >
  <apex:outputPanel id="results">
  
    <table title="CSV Output" border="1" width="100%">
       <apex:repeat value="{!results}" var="row">
           <tr>
               <apex:repeat value="{!row}" var="cell">
                   <td> {!cell} </td>
               </apex:repeat>
           </tr>
       </apex:repeat>
     </table>
  </apex:outputPanel>
  </apex:pageBlock> 

</apex:form> 






public class displayreportextension 
  {    
    String theID;
    public Document d{get;set;}
  
     public displayreportextension()
     {
        theID = ApexPages.CurrentPage().getParameters().get('id');
        d = [select id,name,Body,ContentType from document where id =: theID];
        today=System.Today();

     }
     
    
    public List<List<String>> getResults() 
    {
        List<List<String>> parsedCSV = new List<List<String>>();
        rowCount = 0;
        colCount = 0;
        if (d != null)
        {
            Blob b=d.body;
          
            String fileString = b.toString();
            parsedCSV = parseCSV(fileString, False);
            rowCount = parsedCSV.size();
            for (List<String> row : parsedCSV)
            {
                if (row.size() > colCount)
                {
                    colCount = row.size();
                }
            } 
        }
        return parsedCSV;
    }
    
    public Pagereference CreatePDF()
     {
      pagereference pr = new pagereference('/apex/FinalReport1');
      pr.setredirect(true);
      return pr;
     }
    
    public static List<List<String>> parseCSV(String contents,Boolean skipHeaders) 
     {
        List<List<String>> allFields = new List<List<String>>();
        contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
        contents = contents.replaceAll('""','DBLQT');
        List<String> lines = new List<String>();
        try 
        {
          lines = contents.split('\r'); // using carriage return accomodates windows, unix, and mac files
        }
        catch (System.ListException e) 
        {
            System.debug('Limits exceeded?' + e.getMessage());
        }
        Integer num = 0;
        for(String line: lines) 
        {
           if (line.replaceAll(',','').trim().length() == 0) break;
            List<String> fields = line.split(',');  
            List<String> cleanFields = new List<String>();
            String compositeField;
            Boolean makeCompositeField = false;
            for(String field: fields) 
            {
                if (field.startsWith('"') && field.endsWith('"')) 
                {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
                else if (field.startsWith('"')) 
                {
                    makeCompositeField = true;
                    compositeField = field;
                }
                else if (field.endsWith('"')) 
                {
                    compositeField += ',' + field;
                    cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                    makeCompositeField = false;
                }
                else if (makeCompositeField) 
                {
                    compositeField +=  ',' + field;
                }
                else
                {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
            }
            
            allFields.add(cleanFields);
        }
        if (skipHeaders) allFields.remove(0);
        return allFields;       
     }
     
 
}

 

Thank you

abivenkatabivenkat

 

hi Amit Singh 1989,

 

Find the line of code, where it is causing the error and if it is causing error, while type type conversion, then try converting it with the correct syntax and possibility of conversion.

 

check the file, whether it is a Blob kind of file and check for the contentType of the file which is uploaded in to the document object and then convert it to the native type accordingly and assign to that same type in your apex class.

 

 

 

Thanks,

abivenkat

ramya sfdc 12ramya sfdc 12
HI Amit
request you to please send me code how to cover if else statements and catch block(List exception) as same code I have to submit please help me out 
public List<List<String>> getResults()

    {
      List<List<String>> parsedCSV = new List<List<String>>();

        rowCount = 0;

        colCount = 0;

        if (d != null)

        {
       Blob b=d.body;
      String fileString = b.toString();
      parsedCSV = parseCSV(fileString, False);
      rowCount = parsedCSV.size();
     for (List<String> row : parsedCSV)
    {
    if (row.size() > colCount)
   {
    colCount = row.size();
                }
            }
        }
return parsedCSV;

    }
    public Pagereference CreatePDF()
{
pagereference pr = new pagereference('/apex/FinalReport1');
pr.setredirect(true);
return pr;
}
 public static List<List<String>> parseCSV(String contents,Boolean skipHeaders)
{
 List<List<String>> allFields = new List<List<String>>();
 contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
 contents = contents.replaceAll('""','DBLQT');
 List<String> lines = new List<String>();
 try
{
lines = contents.split('\r'); // using carriage return accomodates windows, unix, and mac files
}
catch (System.ListException e)
{
 System.debug('Limits exceeded?' + e.getMessage());
}
Integer num = 0;
for(String line: lines)
{
if (line.replaceAll(',','').trim().length() == 0) break;
List<String> fields = line.split(','); 
List<String> cleanFields = new List<String>();
String compositeField;
Boolean makeCompositeField = false;
for(String field: fields)
{
if (field.startsWith('"') && field.endsWith('"'))
{
cleanFields.add(field.replaceAll('DBLQT','"'));
}
else if (field.startsWith('"'))
{
makeCompositeField = true;
compositeField = field;
}
else if (field.endsWith('"'))
{
compositeField += ',' + field;
cleanFields.add(compositeField.replaceAll('DBLQT','"'));
 makeCompositeField = false;
}
else if (makeCompositeField)
{
compositeField +=  ',' + field;
}
else
{
 cleanFields.add(field.replaceAll('DBLQT','"'));
}
}
allFields.add(cleanFields);
 }
if (skipHeaders) allFields.remove(0);
return allFields;      

     }
}