i want to Copy & Paste the data from Excel to Datatable using JSF (Primefaces). please suggest me a possibilities to achieve copy & paste.
Asked
Active
Viewed 2,534 times
1
-
let us know if you got something. – ankush yadav Jul 13 '16 at 10:15
-
Do you want to import from an Excel sheet to a datatable programmatically or copy & paste yourself manually? – Tiny Jul 13 '16 at 10:20
-
I want to copy & paste into datatable manually. – Mahendiran Jul 13 '16 at 11:26
-
if i copy data of Excel file and past it into text file, than their is no separate to identified for column than how i can break it into datatable? Beacuse i am thinking to write javascript to take text of pasted text area and convert it into data table. – ankush yadav Jul 13 '16 at 12:17
1 Answers
6
You can listen to a paste event of dataTable primefaces object and get the clipboard data from the event object, format the data to a JSONobject (in the example I used a JSONArray) to send it via remoteCommand to a backingBean.
xhtml:
<p:remoteCommand name="updateData" process="@this" action="#{backingBean.updateData()}" update="dt" />
<p:dataTable widgetVar="dt" id="dt" value="#{backingBean.data}" var="d">
<p:column headerText="column 1">
<p:outputLabel value="#{d.col1}" />
</p:column>
<p:column headerText="column 2">
<p:outputLabel value="#{d.col2}" />
</p:column>
</p:dataTable>
<h:outputScript>
$(function(){
PF('dt').jq.on("paste", function(e){
var data = e.originalEvent.clipboardData;
var table = [];
if(data && data.items && data.items[0]) {
data.items[0].getAsString(function(text){
$.each( text.split("\n"), function(i, r){
table[i] = r.split("\t");
});
updateData([{name: 'data', value: JSON.stringify(table) }]);
});
}
});
});
</h:outputScript>
In your remoteCommand action decode the JSON data and populate the dataTable data provider. Table data is only a Java object with 2 properties (col1 and col2).
BackingBean:
private List<TableData> data;
public List<TableData> getData() {
return data;
}
public void setData(List<TableData> data) {
this.data = data;
}
public void updateData(){
Map<String, String> paramValues = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String json = paramValues.get("data");
JSONArray table = new JSONArray(json);
data = new ArrayList<>();
for (int i = 0; i < table.length(); i++){
JSONArray row = table.getJSONArray(i);
TableData t = new TableData();
for (int j = 0; j < row.length(); j++ ){
String o = row.getString(j);
if (j == 0){
t.setCol1(o);
} else {
t.setCol2(o);
}
}
data.add(t);
}
}
This is only an example, an hint, it needs more work to work properly. Maybe you need a custom primefaces object to do so or extend the PF dataTable.

SiMag
- 586
- 2
- 8
-
Thanks for sharing the code.i'll try above approach and update the staus. Thanks again. – Mahendiran Jul 14 '16 at 03:49