2013-03-19 91 views
4

我正在創建一個應用程序,其中我在圖表和表格中顯示一些數據。現在我希望用戶能夠從表格中複製數據並將其插入到Excel中。我的複製功能工作正常,但輸出有些問題。Javafx複製表格到Excel

舉例來說,如果我想複製下表:

My table

我得到在Excel中下面的輸出:

enter image description here

,如果你不能告訴,該數據顯示在Excel中的單個列中。

有誰知道,我怎麼才能實現正確的輸出,讓每個數據進入一個單獨的列,當粘貼到Excel?

下面是我用複製的代碼:

table.getSelectionModel().setCellSelectionEnabled(true); 
table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); 
MenuItem item = new MenuItem("Kopiér"); 
item.setOnAction(new EventHandler<ActionEvent>() { 
    @Override 
    public void handle(ActionEvent event) { 
     ObservableList<TablePosition> posList = table.getSelectionModel().getSelectedCells(); 
     int old_r = -1; 
     StringBuilder clipboardString = new StringBuilder(); 
     for (TablePosition p : posList) { 
      int r = p.getRow(); 
      int c = p.getColumn(); 
      Object cell = table.getColumns().get(c).getCellData(r); 
      if (cell == null) 
       cell = ""; 
      if (old_r == r) 
       clipboardString.append('\t'); 
      else if (old_r != -1) 
       clipboardString.append('\n'); 
      clipboardString.append(cell); 
      old_r = r; 
     } 
     final ClipboardContent content = new ClipboardContent(); 
     System.out.println(clipboardString); 
     content.putString(clipboardString.toString()); 
     Clipboard.getSystemClipboard().setContent(content); 
    } 
}); 
MenuItem item2 = new MenuItem("Kopier række"); 
item2.setOnAction(new EventHandler<ActionEvent>() { 
    @Override 
    public void handle(ActionEvent event) { 
     String rowContent = ""; 
     ObservableList<TablePosition> posList = table.getSelectionModel().getSelectedCells(); 
     System.out.println(rowContent); 
     for (TablePosition p : posList) { 
      int c = 1; 
      int row = p.getRow(); 
      System.out.println("c " +c); 
      System.out.println("row "+row); 
      for (int i = 1; i < table.getColumns().size(); i++) { 
       rowContent = rowContent +" "+table.getColumns().get(c).getCellData(row); 
       if (c < 13) { 
        c++;    
       } 
      }  
     } 
     final ClipboardContent allContent = new ClipboardContent(); 
     allContent.putString(rowContent.toString()); 
     Clipboard.getSystemClipboard().setContent(allContent); 
     System.out.println(allContent.toString()); 
     rowContent = ""; 
    } 
}); 
ContextMenu menu = new ContextMenu(); 
menu.getItems().addAll(item,item2); 

回答

6

添加列之間的製表\t。 Excel應該認識到這一點並使用新的單元格。它通過使用選項卡並將其粘貼到Excel中時將其寫入記事本中。

+0

謝謝你傻我:) – 2013-03-19 13:05:37