Insert image in excel using javascript - javascript

My html page contain a embedded image (png) that I like to insert into the excel file dynamically. I tried below that created the excel file with the name I like and a worksheet name as well * though the name of worksheet is same as file name, not sure how to set that, with below code
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
var postfix = 'AKS'
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('myDynamicImage');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
But the content of image in dataURI format is inserted in excel as a text rather then image. Can I setup this for image. can I control the position etc. can i control the worksheet name, I did that with some other but bit complicated way called tableToExcel.

Related

Issue with Unicode characters in photoshop javascript code

I have created a JSX for reading the data from TAB delimited input file (input file has two columns; ID and description). I want to read the input file and place the description on text layer and save the filename with ID.
It works when the description field letters and numbers. But it does not work when it has (é) in the description.
var Description = "on the ***pavé***";
textlayer.textItem.encoding = "UTF-8";
textlayer.textItem.contents = Description;
textlayer.textItem.tracking =50;
textlayer.textItem.wrapBend=70;
var saveFile = new File(outputfolder + "\\" + ID + "_16.psd");
saveFile.encoding="UTF-8";
app.activeDocument.saveAs( saveFile, saveOptions, true );
Works for me:
// Switch off any dialog boxes
displayDialogs = DialogModes.NO; // OFF
var outputfolder = "C:\\temp";
var description = "pavé_16";
var mySaveFile = outputfolder + "\\" + description + ".psd";
var psdFile = new File(mySaveFile);
activeDocument.saveAs(psdFile, SaveDocumentType.PHOTOSHOP, true, Extension.LOWERCASE);
displayDialogs = DialogModes.ALL; // NORMAL
Are you sure you're saving out as pavé_16.psd and not ***pavé***_16.psd? As asterisks (stars) in your filename will not work :)

exporting html table with links to csv

I am using the following function to export a table to a csv file for our users to export a copy of their purchases to a format they can use in quickbooks, excel, etc.
The function works great, except that the first column of our table contains urls and these columns appear blank in the export.
I am wondering how i could modify this so when a link is encountered as a field the text of that link would be added to the csv.
Example: an example would add an example to the csv for that field.
function exportTableToCSV($table, filename) {
var $rows = $table.find('tr:has(td),tr:has(th)'),
tmpColDelim = String.fromCharCode(11), // vertical tab character
tmpRowDelim = String.fromCharCode(0), // null character
colDelim = '","',
rowDelim = '"\r\n"',
csv = '"' + $rows.map(function (i, row) {
var $row = $(row), $cols = $row.find('td,th');
return $cols.map(function (j, col) {
var $col = $(col), text = $col.text();
return text.replace(/"/g, '""'); // escape double quotes
}).get().join(tmpColDelim);
}).get().join(tmpRowDelim).split(tmpRowDelim).join(rowDelim).split(tmpColDelim).join(colDelim) + '"',
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csv);
console.log(csv);
if (window.navigator.msSaveBlob) { // IE 10+
window.navigator.msSaveOrOpenBlob(new Blob([csv],
{type: "text/plain;charset=utf-8;"}),
"csvname.csv")
} else {
$(this).attr({ 'download': filename, 'href': csvData, 'target': '_blank' });
}
}
As far as I can see, your snippet should already support this. It iterates over all rows of the table and for each row over all of its column fields, where jQuery's text() function is applied in order to extract the text. This should return the text between a tags as well.
Example:
console.log($('<td>Test page</td>').text());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
will return the string Test page.
This fiddle contains the function you provided and a dummy table with some anchor elements. In my opinion it already meets your requirements.
var a = document.createElement('a');
a.href = "http://example.php";
a.append("an example");
document.body.appendChild(a);
console.log(a.textContent);

How to add Comment in CSV Header using JavaScript/JQuery

I want to add a comment on Header fields of CSV File generated by Javascript
Also, I have Searched out for these requirements but can't find any solutions
Here is code that's using for generating CSV File using Javascript
var data = [
['123'],
['346'],
['789'],
['Test1'],
['Test2']
];
function download_csv() {
var csv = 'ID\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log(csv);
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'test.csv';
document.getElementById('container').appendChild(hiddenElement);
hiddenElement.click();
}
<button onclick="download_csv()">Download CSV</button>
<div id="container" style="display:none;"></div>
I want to Add Header Comment like Here
There is no standard way to achieve this using CSV. However, you can resort to writing the file as XLXS as commenting is an application specific feature.

Downloading file made with jquery's .innerhtml breaks at the first "#"

I have this code:
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //displays fine
a.href = "data:image/svg+xml," + dd.innerHTML;
a.click();//downloaded file cuts off at the first "#"
}
When the alert displays it it's okay, the downloaded version is cut off before the first "#". How do I fix this?
Since this is part of a href, you need to url-encode your data first, eg.
function download()
{
var a = document.body.appendChild(document.createElement("a"));
a.download = "CalExport.svg";
var dd = document.getElementById('SvgResult');
alert(dd.innerHTML); //should still display fine
a.href = "data:image/svg+xml," + encodeURIComponent(dd.innerHTML);
a.click();//should now not cut off.
}
The safe variation of # in a url is %23%0A (check out this tool: http://meyerweb.com/eric/tools/dencoder/).

create a downloadable csv from a json string

Target: write&download a csv file starting with a json string, for example data.csv containing
col1,col2,col3
"324","19-08-2014","13000"
"325","19-08-2014","5010"
What I have done until now:
1) iframe and button to call my conversion function
<iframe id="frame" style="display:none"></iframe>
<form><input type="submit" value="Export CSV" onclick="javascript:Download();"></form>
2) my Download() function which would want to download my csv file
<script type="text/javascript">
function Download(){
var csv=ConvertToCSV(<?php echo $json_string ?>);
var url='data:application/csv,'+csv;
var _iframe_dl = $('<iframe />')
.attr('src', url)
.hide()
.appendTo('body');
};
</script>
3) my json to csv conversion function which tries to create a csv string
<script type="text/javascript">
function ConvertToCSV(json) {
var array = typeof json != 'object' ? JSON.parse(json) : json;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += '"'+array[i][index]+'"';
}
str += line + "\r\n";
}
return str;
}
</script>
Encountered problems :
i) it seems that it doesn't recognize \r\n, infact output is just one line
"324","19-08-2014","13000""325","19-08-2014","5010"
ii) I cannot set the filename and the extension, infact the downloaded file is "download" without extension containing the single line mentioned above
First of all, you will need to ensure your data is in this format, like the example below.
var array = [["col1","col2","col3"],["324","19-08-2014","13000"],["324","19-08-2014","13000"]]
then you need to create csv variable as shown below
var csv = "data:text/csv;charset=utf-8,";
after this you need to loop through your data array and append each line to the csv variable you just set.
array.forEach(function(arrayItem, index){
arrayAsString = arrayItem.join(",");
csv += index < array.length ? arrayAsString+ "\n" : arrayAsString;
});
now to give this file a name and create a download link you must create a hidden anchor node and set its download attribute.
var encUri = encodeURI(csv);
var link = document.createElement("a");
link.setAttribute("href", encUri);
link.setAttribute("download", "file_name.csv");
//add anchor element to body
document.body.appendChild(link);
link.click();
EDIT:
Tested on Chrome and is working, also on Safari. Does not work on Firefox for some reason which i will take a look at now
I found out that if you add the link into the body of the page only then will Firefox initiate the download, you can use a code like so. I have updated my code above
document.body.appendChild(link);

Categories