Reputation: 1197
I am trying to create a CSV file from a dynamically generated table.I have a code which generates a reasonable CSV.The output of the code is
, Emp I D, Emp Name, Emp Title,
, 111 , andro1 , developer ,
, 112 , andro2 , developer ,
, 113 , andro3 , developer ,
I would like to remove the commas at the beginning of each line so the csv is well formatted.I also would like to neatly format this CSV so that it opens properly in excel(with heading in bold ,well spaced coulmns etc).
I am pasting the sample javascript used by me
//Modify the value of these variable for your coach
var tableIdsToExport = "Table0";
// a comma delimited list of the ids of the tables that you want to include in the excel export
// if you include a tableId that does not exist in your coach, you will recieve a client side error message
//You do not need to modify the following part of the script
var form = document.createElement('div');
form.innerHTML = '<form name="exportData" method="post" target="_new" action="data-redirect.jsp"><input type="hidden" name="contentType" value="text/csv"><input type="hidden" name="data" value=""><input type="hidden" name="fileName" value="filename=reportData.csv"></form>';
//Work around a bug in IE: http://support.microsoft.com/default.aspx/kb/927917
document.getElementsByTagName("H1")[0].appendChild(form);
//document.body.appendChild(form);
function addExportData(csvTable) {
if (document.forms.exportData == null || document.forms.exportData.data == null) {
return;
}
document.forms.exportData.data.value = document.forms.exportData.data.value +
"\n\n" + csvTable;
}
function doSubmitExport() {
var tableArr = tableIdsToExport.split(",");
for (var i=0;i<tableArr.length;i++) {
addTableToCSV(tableArr[i]);
alert(addTableToCSV(tableArr[i]));
}
document.forms["exportData"].submit();
}
function addTableToCSV(tableId) {
var table;
try {
table = document.getElementById(tableId);
var a = table.innerHTML;
//replace existing commas with semi-colons. Poor mans way of handling embedded commas in a csv file
a = a.replace(/,/g, ";");
//get rid of javascript blocks
a = a.replace(/<script(.|\n)*?<\/script>/gi, "");
//insert commas at the end of a table cell
a = a.replace(/<\/td>/g, ",");
a = a.replace(/<\/TD>/g, ",");
a = a.replace(/<\/th>/g, ",");
a = a.replace(/<\/TH>/g, ",");
//insert a newline tag at the end of every row. Need to do this before removing all tags
a = a.replace(/<\/tr>/g, "---newline---");
a = a.replace(/<\/TR>/g, "---newline---");
//remove html tags
a = a.replace(/<\/?[^>]+(>|$)/g, "");
//remove whitespace (regexs found via google)
a = a.replace(/\r/g, " ");
a = a.replace(/[^ A-Za-z0-9`~!@#\$%\^&\*\(\)-_=\+\\\|\]\[\}\{'";:\?\/\.>,<]/g, "");
a = a.replace(/'/g, "");
a = a.replace(/ +/g, " ");
a = a.replace(/^\s/g, "");
a = a.replace(/\s$/g, "");
//put newlines in
a = a.replace(/---newline---/g, "\n");
//replace   which the coach designer inserts
a = a.replace(/\ /g, " ");
//a now holds a resonable csv that I can put in excel
//alert(a);
addExportData(a);
return true;
} catch (e) {
alert("Table Export Error: " + e);
}
return true;
}
</script>
One more thing is, in the table there is a column which is empty.that is the reason that the script is returning a comma at the beginning which I would like to remove. when I try to open the csv in excel the content starts at the third row instead of the first row.
This is being used in IBM BPM Lombardi application where I am trying to export a a dynamically generated table to excel.
I would also like know how the same result can be achieved through jquery Thanks in advance
Once this is done I am also planning an export to pdf option.
the following expalins what is being done in the script
The key component that performs the export is a Custom HTML code block that contains client-side JavaScript. The JavaScript contains the following components:
1.A JavaScript variable tableIdsToExport. This is a comma-delimited string that itemizes the table element ids to be exported. You must ensure that the ids match those in your Coach.
2.A JavaScript variable form that is a dynamically generated HTML form element (not displayable). The URI for the action attribute of this form is a Teamworks JSP that will return the spreadsheet. This form also contains an input field data that contains the table(s) to be exported.
3.An 'Export to excel' button. When this this button is selected the doSubmitExport function is executed.
4.doSubmitExport function. The algorithm for this function performs two tasks. First, it iterates over each table in tableIdsToExport and calls the addTableToCSV function. After the iteration is complete the function submits the form element contained in the form variable (above).
5.addTableToCSV function. This function is called for each table in the tableIdsToExport list and has two basic tasks to perform. First, the HTML table is transformed such that the table elements are replaced by commas and line feeds effectively transforming the table into a CSV. Next, the addTableToExport function is called with the transformed table passed as a parameter.
6.addTableToExport function. This function takes a parameter that is the CSV and appends it to the hidden form's data field. Upon submission, the form is posted to the Teamworks data-redirect.jsp which applies the appropriate content type and sends the data back to the browser.
Upvotes: 0
Views: 3534
Reputation: 15319
I agree with David Thomas, when he says that you should fix problem in the CSV generation script.
But if you don't have control over that script, you can use regular expressions in the javascript replace()
to replace the first occurrence of a comma with an empty string (removing it):
", 111 , andro1 , developer ,".replace(/^,/, '');
that returns:
" 111 , andro1 , developer ,"
Update:
Here you can see a demo of a javacript that removes the first comma and justifies all columns to a predefined max width.
Since you don't have a jQuery tag, I am assuming you want pure Javascript, but keep in mind that with jQuery would be much easier.
The final output you can see from the demo, is
EmpID, EmpName, EmpTitle,
111, andro1, developer,
112, andro2, developer,
113, andro3, developer,
In this case I am right justifying each column to 10 characters.
About the bold in columns title, that is not possible in CSV format, because CSV is a plain text format. You might consider for this xlwt.
Again, I agree that you should solve this formatting problem from the generating script, but if you are just the consumer of those files and want to fix them in javascript, then this solution should work for you.
Update 2 You need to clean that javascript. Please read the regexp link that I included above.
You can replace this:
a = a.replace(/<\/td>/g, ",");
a = a.replace(/<\/TD>/g, ",");
a = a.replace(/<\/th>/g, ",");
a = a.replace(/<\/TH>/g, ",");
with simply this:
a = a.replace(/<\/t(d|h)>/gi, '');
And why are you replacing </tr>
and </TR>
with --newline--
and then again you replace --newline--
with \n
? You could simply do this in a single call:
a = a.replace(/<\/tr>/gi, '\\n');
So, I think you end up having a single string with all csv content, where each row is separated by a \n
.
Here is the updated script to handle this use case. I only changed the var
declaration, the core remains the same.
Upvotes: 2
Reputation: 626
And for formatting the expressions, regular expression will not come to your rescue. That formatting must be done in your CSV generation script.
Upvotes: 0