2011-08-20 40 views

回答

0

如果要將字符串值導出爲csv文件(excel支持它),或者可以使用其他庫(例如Apache POI)。

public static void exportJTable (JTable table, String fileName) throws Exception { 
    StringBuilder content = new StringBuilder(""); 

    for (int i=0; i<table.getModel().getRowCount(); i++){ 
     for (int j=0; j<table.getModel().getColumnCount(); j++) { 
      int col = table.convertColumnIndexToView(j); 
      String value = null ; 

      try { 
       value = (String) table.getModel().getValueAt(i, col); 
      } 
      catch (java.lang.ClassCastException e) { 
      } 

      if (value == null) 
       value = "" ; 

      // CSV file 
      value.replaceAll(",", ""); 
      content.append(value + ","); 
     } 
     content.append("\n"); 
    } 


    writeToFile(content.toString(),fileName); 
} 

private static void writeToFile (String data, String fileName) throws FileNotFoundException, UnsupportedEncodingException { 
    File file = new File(fileName); 
    PrintWriter writer = new PrintWriter(file,"UTF-8"); 

    writer.println(data); 

    writer.close(); 
} 
+0

a)-1用於類型轉換爲字符串b)-1用於將model-columnIndex轉換爲視圖座標,然後用它查詢模型,c)導出_color_會在你的代碼片段中的哪個地方得到解決? – kleopatra