Tuesday, February 15, 2005

ASP.NET Datagrid to Excel clipboard copy/paste: an ugly javascript solution

As usual this one is a crazy reqt to provide a feature to copy/paste a fixed size datagrid to/from excel. To me * should understand the architectural difference between a web form and winform There are some inherent features that comes with winform; and one should not expect, all the features to be provided in webform. "He who gives me salt, he shall get the solution", i found excel reads/writes data in clipbooard with tab delimited for columns and new line delimited for rows,

function GetExcelData(){
var content = clipboardData.getData("Text");
if (content!=null) {
     var t = content.replace(/\n/g," \n");
     t = t.replace(/\t/g," \t");
     var myArray = t.split(/\n/);
     var y = "<table align='center' border='1'>";
     for (var i = 0; i < myArray.length; i++) {
          y = y + "<tr>";
          var myArray2 = myArray[i].split(/\t/);
          for (var j = 0; j < myArray2.length; j++) {
               y = y + "<td> " + myArray2[j] + "</td>";
          y = y + "</tr>";
     y = y + "</table>";
     window.spnMsg.innerHTML = y;
else {
     window.spnMsg.innerHTML = "No text found in clipboard.";

function PutExcelData(){ //... build a string in delimited format and put it in clipboard

Proposed solution is to provide a button "Copy", to copy the data from datagrid to clipboard and a "Paste" button to copy the data data from clipboard to datagrid.

Warning: Not sure if it is supported in all IE versions and other GOOD browsers like Firefox.

I found a workaround also, use a textarea form field that holds the text to be copied, select it by form.textarea.select() method and copy it to the clipboard using the execCommand like below, Unfortunately the select() method works with visible form objects only, that can be easily overcomed but putting that control in a div tag and making the div tag invisible.


It struck me after coding the solution, how easy it will be to exploit this and steal a sensitive information from clipboard (i know many copy/paste passwords, credit card nbrs!). I expect IE to atleast prompt user, before allowing this script to access clipboard.

No comments: