For a project, I needed to cut, copy and paste from a Java JTable to Excel. The KeyAdapter I ended up writing is below. As it turns out, there is another similar version online from 1999 at Javaworld (I borrowed the contiguous block check from this code, as I hadn’t previously considered that possibility) – but I like mine better.
To copy to Excel, a Java program must put the data onto the clipboard in a format Excel understands. The easiest way to do this is to use a String, structured as a series of cells separated by tabs and rows separated by line breaks. To read in data Excel puts on the clipboard, is just a matter of parsing a similarly structured String. There are other data formats available on the clipboard, but just using plain text is all that was needed for my requirements. However if you need to escape tabs and line breaks in your data then it might be worth investigating them. The code below just converts tabs and line breaks to spaces when copying to the clipboard, and ignore them when reading in (as tabs can’t be in an Excel cell and I couldn’t see how to detect line breaks in a cell rather than separating lines). To use this class just add it as a KeyListener on the table (JTable.addKeyLisenter).