Sometimes we need to read a csv file in a visualforce page.
Here is a example to read a csv file and display it in a pageblocktable.
Following example reads a csv file having account records in it and displays them in a table when "Read csv" button is pressed.
Csv file format used in this example:
Output screen shot:
Visualforce page
Controller
Here is a example to read a csv file and display it in a pageblocktable.
Following example reads a csv file having account records in it and displays them in a table when "Read csv" button is pressed.
Csv file format used in this example:
Output screen shot:
Visualforce page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| <apex:page controller="csvFileReaderController"> <apex:form > <!-- csv reader demo --> <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.Accountsource}" /> <apex:column value="{!rec.Type}" /> <apex:column value="{!rec.Website}" /> </apex:pageblocktable> </apex:pageBlock> </apex:form></apex:page> |
Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
| Public with sharing class csvFileReaderController {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 csvFileReaderController(){ 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.website = csvRecordData[3]; accRec.AccountSource = csvRecordData[4]; sObjectList.add(accRec); } }} |


Error Error: csvFileReaderController Compile Error: Illegal assignment from LIST to LIST at line 11 column 5
ReplyDelete