Clipboard formats
When you copy data from an application, it sends different pieces of data, on different formats, to the clipboard. As a result, you can do things as copying a file and then paste the actual file on a directory or just its path on a text document.
Likewise, an application is ready to understand a certain set of formats.
Some of these formats are standard. Others, are custom formats unique to an application. Maybe you want to read about clipboard formats on Windows and, mainly, the article provided by @Tim Williams.
You need to find a format that both Excel and your supported browsers can understand.
This other answer list some formats used by Excel. The Clipboard API and events W3C Working Draft enforces some mandatory data types.
In a slightly different scenario, I copied a range of cells from LibreOffice Calc to Firefox on my Linux machine. I can get a list of valid data formats for the current selection by using xclip
:
xclip -selection clipboard -o -t TARGETS
As per @Tim Williams' link you can use a tool called cbdump
on Windows. It seems that it is not available any longer; the OP found a similar one called clipview.
It returns around 20 formats, half of them exclusive to OpenOffice (application/x-openoffice-...
). Just two were supported by my browser (the rest return an empty string): text/plain
and text/html
.
Under text/plain
format, the browser pastes the text inside the cells as you see it (1.26, not the real value 1.2562) and that makes sense. Under text/html
it returns a very verbose output, including the cell value:
<!-- more html -->
<td height="34" align="right" sdval="1.2562">1.26</td>
<!-- more html -->
Set clipboard format in JavaScript
Once you know which is your target format, you can use ClipboardEvent.clipboardData
:
- to obtain the data to be pasted from the
paste
event handler, typically with a getData(format)
call.
format
is a DOMString representing the type of data to retrieve.
var textArea = document.querySelector('textarea');
textArea.addEventListener('paste', function(e) {
var format = document.querySelector('input[name="format"]:checked').value;
e.preventDefault();
var excel_data = (e.originalEvent || e).clipboardData.getData(format);
textArea.value = excel_data;
});
<input id="plainText" type="radio" name="format" value="text/plain" checked>
<label for="plainText">plain text</label>
<input id="HTML" type="radio" name="format" value="text/html">
<label for="html">HTML</label>
<p>Paste excel data here:</p>
<textarea></textarea>