Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
package com.sieuferd.harness;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.SystemFlavorMap;
import java.awt.datatransfer.Transferable;
public final class FlavorMapBugExhibit {
public static final boolean ENABLE_WORKAROUND = false;
private FlavorMapBugExhibit() { }
/* To test, open Microsoft Excel for Mac 2011, select a few cells, and invoke "Copy" to copy the
cells to the clipboard. Then run this class. When ENABLE_WORKAROUND is false, an
UnsupportedFlavorException will be thrown. The bug does not exist on Windows (tested with
Excel 2013). */
public static void main(String args[]) throws Exception {
DataFlavor dataFlavor = registerExcelDataFlavor();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = clipboard.getContents(null);
try (InputStream is = (InputStream) transferable.getTransferData(dataFlavor)) {
// Should print 208, 207.
private static DataFlavor registerExcelDataFlavor() throws Exception {
// See .
final boolean isMacOS = System.getProperty("").contains("Mac OS X");
final String nat = isMacOS
// Tested with Excel for Mac 2011.
? "CorePasteboardFlavorType 0x454D4253"
// Tested with Excel for Windows 2013.
: "Biff8";
DataFlavor result = new DataFlavor("application/", "Excel BIFF8");
SystemFlavorMap map = (SystemFlavorMap) SystemFlavorMap.getDefaultFlavorMap();
map.addUnencodedNativeForFlavor(result, nat);
map.addFlavorForUnencodedNative(nat, result);
// Workaround for the exhibited bug.
/* Force calling of DataTransferer.getFormatForNativeAsLong, which is necessary for getting
indexForFormat to return a valid index when CClipboard.getClipboardFormats in
macosx/native/sun/awt/CClipboard.m calls it. */
sun.awt.datatransfer.DataTransferer.getInstance().getFormatsForFlavor(result, map);
return result;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment