printing an html table using javascripting

L

lisha

I have code which generates html table on the fly and fills it up with
data. i have to add a print button so that i am able to print the
output in html table to the printer. Also, is it possible to print it
to an excel file?
 
S

shimmyshack

_printing_ to an excel file?
you could post a tab, comma or json formatted string to an ultra simple
server side script that just sends it straight back, with an excel
mimetype
<?php
header('Content-Type: application/vnd.ms-excel');
header('Content-Length: '.strlen($_POST['javascript_csv_string']));
echo $_POST['javascript_csv_string'];
exit;
?>
obviously this would allow people to post stuff to your webserver which
would then appear to be downloaded from you, so you would have to
implement some checking.

As for doing it straight from javascript, unless it is possible to use
an XHR call, inject client side data instead of a server response
payload, and setting the right headers. Perhaps, Ive never tried it.

however it is possible with an iframe, using this code
<html>
<head></head>
<body>
<iframe src="" id="file" name="file"></iframe>
<script type="text/javascript">
document.getElementById('file').src =
"data:application/vnd.ms-excel;base64,MSwyLDMsNA==";
</script>
</body>
</html>

you could use application/csv or text/csv instead of
application/vnd.ms-excel but then it isnt automatically opened as
required. Basically its a quick and dirty "yes you can" but how clean
you could get it, my opinion would be to try to use the header settings
power of XHR, together with some trickery to load the return call of
the XHR with data thats already hanging around, and have XHR do a call
that gets intercepted anyway.

Erm.... the fly in the ointment to all this, the Multi-$B company
Microsoft, who squeezed a few more millions into their bank account by
not bothering to implement the data url. sorry - this trick only works
in compliant browsers like Safari/Firefox/Opera and so on... IE7? hmm
let me guess.
 
S

shimmyshack

oh I should have said, you will need a javascript implementation of
base64 so you can encode the csv string generated by js,
in this case
1,2,3,4
is
MSwyLDMsNA==
in base64

there are license free base64_encoders around for js.
Ive tested this on linux too, using the vnd.ms-excel forces an open
into openoffice if installed. As I say the only spanner in the works is
IE.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top