Thursday, May 01, 2008

Read and parse Excel data from clipboard using Javascript

IE7 prevent clipboard from being read - you can enable it in the title-bar (blocked content). For Firefox read this info.
Following sample reads data from clipboard and tries to parse them and format back to table.

// prepare result
var resE = document.getElementById("result");
var res = "";
resE.innerHTML = "";
// read clipboard
var s = window.clipboardData.getData("Text");
// parse clipboard data
var lines = s.split(String.fromCharCode(13,10));
if (s.indexOf(String.fromCharCode(13,10)) == -1 || s.indexOf(String.fromCharCode(9)) == -1)
{
res = "(invalid data)";
}
else
{
var cols = lines[0].split(String.fromCharCode(9));
res = "Table size: " + lines.length + "x" + cols.length + "
";
res += "";
var i = 0, j = 0;
for(i = 0; i < lines.length; i++)
{
res += "";
cols = lines[i].split(String.fromCharCode(9));
for(j = 0; j < cols.length; j++)
res += "
" + (cols[j] == "" ? "~" : cols[j]);
}
res += "
";
}
// output result
resE.innerHTML = res;