2017-04-23 31 views
12

我試圖將我的JTable導出爲Excel文件。列和行名稱都很好,但我添加到JTable中的所有信息都沒有寫入。我試過System.out.println()和它打印價值無處不在列和行名稱。我試圖從母親谷歌的答案,但經過2個小時的閱讀和嘗試,仍然沒有進展。 我的腦海中仍然存在的問題是,在寫入Excel部分代碼時可能會出現一些錯誤,或者添加到JTable的所有內容都只是顯示器上的圖片,而不是實際的數據。 糾正我,如果我錯了,並高度讚賞任何幫助。EDITED將JTable寫入Excel

這是寫入Excel部分。 在第一個For循環中,我得到的標題和在第二個For循環中,我應該得到我的JTable裏面的所有東西,但我不是。

TableColumnModel tcm = nrp.rotaTable.getColumnModel(); 

    String nameOfFile = JOptionPane.showInputDialog("Name of the file"); 

    Workbook wb = new HSSFWorkbook(); 
    CreationHelper createhelper = wb.getCreationHelper(); 

    Sheet sheet = wb.createSheet("new sheet"); 
    Row row = null; 
    Cell cell = null; 

    for (int i = 0; i < nrp.tableModel.getRowCount(); i++) { 
     row = sheet.createRow(i); 
     for (int j = 0; j < tcm.getColumnCount(); j++) { 

      cell = row.createCell(j); 
      cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString()); 

     } 
    } 
    for (int i = 1; i < nrp.tableModel.getRowCount(); i++) { 
     row = sheet.createRow(i); 
     System.out.println(""); 
     for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) { 

      cell = row.createCell(j); 
      cell.setCellValue((String) nrp.tableModel.getValueAt(i, j)+" "); 
      System.out.print((String) nrp.tableModel.getValueAt(i, j)+" "); 
     } 
    } 


    File file = new File("Some name.xls"); 
    FileOutputStream out = new FileOutputStream(file); 
    wb.write(out); 
    out.close(); 
    wb.close(); 
    } 
} 

這裏是FocusListener代碼。

rotaTable.addFocusListener(new FocusListener() { 
      public void focusGained(FocusEvent e) { 
      } 
      public void focusLost(FocusEvent e) { 
       CellEditor cellEditor = rotaTable.getCellEditor(); 
       if (cellEditor != null) 
        if (cellEditor.getCellEditorValue() != null) 
         cellEditor.stopCellEditing(); 
        else 
         cellEditor.cancelCellEditing(); 
      } 
     }); 

我使用 '的DefaultTableModel'

DefaultTableModel tableModel = new DefaultTableModel(12,8); 
JTable rotaTable = new JTable(tableModel); 

這是第一次,當我與POI庫工作。在控制檯打印結果我的JTable http://imgur.com/a/jnB8j

圖片的

圖片http://imgur.com/a/jnB8j

Excel文件的圖片創建。 http://imgur.com/a/jnB8j

+0

在第二個「for」中,爲什麼不從0開始? –

+0

也許你必須將'cell.setCellValue((String)nrp.tableModel.getValueAt(i,j)+「」);'..改成這個'cell.setCellValue((String)tcm。getValueAt(i,j)+「」);' –

+0

如果沒有更多的信息很難說,你可能會引用錯誤的模型 – MadProgrammer

回答

4

你必須0開始行索引,因爲錶行是從0開始,從1創建EXCEL行,因爲第一次爲你寫列names.I修改你的第二個for循環是這樣的:

for (int i= 0; i < nrp.tableModel.getRowCount(); i++) { 
    row = sheet.createRow(i+1); 
    System.out.println(""); 
    for (int j = 0; j < nrp.tableModel.getColumnCount(); j++) { 
     cell = row.createCell(j); 
     if(nrp.tableModel.getValueAt(i, j)!=null){ 
     cell.setCellValue((String) nrp.tableModel.getValueAt(i, j)); 
     } 
     System.out.print((String) nrp.tableModel.getValueAt(i, j)+" "); 
    } 
} 
+0

http://imgur.com/LxxdD19沒有改變,相同的輸出,只有空值不復制到Excel文件。 – Helvijs

1

一旦我編寫了這段代碼,就可以將一組JTables寫入Excel文件(一個接一個)。我可以看到它幾乎與你寫的代碼相同。你可以試試這個,而不是你阻止。您必須更換輸入對象或包裝你的表成地圖

for (int i = 1; i < nrp.tableModel.getRowCount(); i++) { 
... 
} 

因爲我需要寫一個挨着另一個我使用的變量FILA和columna來獲得當前位置,把下一個表的表。 您可以將它們設置爲0或1以便進行測試。 也許它可以幫助你帶來新的想法。

此外,我注意到的唯一區別是:如果 (行== NULL){...}

private void escribirContenido(Sheet hoja, Entry<String, JTable> e) { 
    Row row; 
    Cell cell; 
    for (int i = fila; i < e.getValue().getRowCount() + fila; i++) { 
     row = hoja.getRow(i); 
     if (row == null) { 
      row = hoja.createRow(i); 
     } 
     for (int j = 0; j < e.getValue().getColumnCount(); j++) { 
      cell = row.createCell(j + columna); 
      String value = String.valueOf(e.getValue().getValueAt(i - fila, j)); 
      try { 
       cell.setCellValue(new Double(value)); 
      } catch (NumberFormatException e1) { 
       cell.setCellValue(value); 
      } 
     } 
    } 
} 
0
import java.awt.Color; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.ResultSetMetaData; 
import java.sql.SQLException; 
import java.sql.Statement; 
import java.util.ArrayList; 
import java.util.Vector; 

import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.ListSelectionModel; 

import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.CreationHelper; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Sheet; 
import org.apache.poi.ss.usermodel.Workbook; 

@SuppressWarnings("serial") 
public class EmployeePanel extends JPanel { 
    public ArrayList columnNames = new ArrayList(); 
    ArrayList data = new ArrayList(); 
    Connection conn; 
    String query; 
    String sql = "SELECT * FROM employee"; 
    String url = "jdbc:mysql://localhost:3306/nandos_db"; 
    String userid = "User1"; 
    String password = "Password1"; 
    Statement stmt; 
    ResultSet rs; 
    int rows = 0; 
    int columns = 0; 
    JTable employeeTable; 

    @SuppressWarnings({ "unchecked" }) 
    public EmployeePanel() { 
     super(); 
     this.setBackground(Color.GREEN); 
     this.setLayout(null); 
     this.setVisible(true); 
     try { 
      conn = DriverManager.getConnection(url, userid, password); 
      stmt = (Statement) conn.createStatement(); 
      rs = stmt.executeQuery(sql); 
      ResultSetMetaData md = (ResultSetMetaData) rs.getMetaData(); 

      int columns = md.getColumnCount(); 
      for (int i = 1; i <= 3; i++) { 
       columnNames.add(md.getColumnName(i)); 
      } 
      while (rs.next()) { 
       ArrayList row = new ArrayList(columns); 
       for (int i = 1; i <= columns; i++) { 
        row.add(rs.getObject(i)); 
       } 
       data.add(row); 
      } 
      // Get row data 
     } catch (SQLException e) { 
      // System.out.println(e.getMessage()); 
      e.printStackTrace(); 
     } 
     // Create Vectors and copy over elements from ArrayLists to them 
     // a custom defined class which inherits from the AbstractTableModel 
     // class 
     Vector columnNamesVector = new Vector(); 
     Vector dataVector = new Vector(); 
     for (int i = 0; i < data.size(); i++) { 
      ArrayList subArray = (ArrayList) data.get(i); 
      Vector subVector = new Vector(); 
      for (int j = 0; j < subArray.size(); j++) { 
       subVector.add(subArray.get(j)); 
      } 
      dataVector.add(subVector); 
     } 
     for (int i = 0; i < columnNames.size(); i++) { 
      columnNamesVector.add(columnNames.get(i)); 
     } 
     // Create table with database data 
     employeeTable = new JTable(dataVector, columnNamesVector); 
     employeeTable.getTableHeader().setOpaque(false); 
     employeeTable.getTableHeader().setBackground(Color.pink); 
     employeeTable.setBackground(Color.orange); 
     employeeTable.setSelectionMode((ListSelectionModel.SINGLE_SELECTION)); 
     employeeTable.setEnabled(true); 
     employeeTable.setDragEnabled(false); 
     employeeTable.setCellEditor(null); 

     JScrollPane sp = new JScrollPane(employeeTable); 
     sp.setSize(1030, 540); 
     sp.setLocation(10, 10); 
     this.add(sp); 
    } 

    public static void main(String... args) throws IOException { 
     JFrame f = new JFrame(); 
     EmployeePanel t = new EmployeePanel(); 
     f.add(t); 
     f.setVisible(true); 
     f.pack(); 

     System.out.println(t.employeeTable.getValueAt(0, 0)); 

     Workbook wb = new HSSFWorkbook(); 
     CreationHelper createhelper = wb.getCreationHelper(); 

     Sheet sheet = wb.createSheet("new sheet"); 
     Row row = null; 
     Cell cell = null; 
     row = sheet.createRow(0); 
     for (int i = 0; i < t.employeeTable.getColumnCount(); i++) { 
      cell = row.createCell(i); 
      cell.setCellValue(String.valueOf(t.employeeTable.getColumnName(i))); 
     } 

     for (int j = 1; j <= t.employeeTable.getRowCount(); j++) { 
      row = sheet.createRow(j); 
      for (int i = 0; i < t.employeeTable.getColumnCount(); i++) { 
       cell = row.createCell(i); 

       cell.setCellValue(String.valueOf(t.employeeTable.getValueAt(j - 1, i))); 

      } 
     } 

     File file = new File("C:\\Users\\test\\Desktop\\Some name.xls"); 
     FileOutputStream out = new FileOutputStream(file); 
     wb.write(out); 
     out.close(); 
     wb.close(); 

    } 

} 

,如果我讓這個代碼連接到我的數據庫,生病得到一個Excel工作表與框架中的表格完全相同。因爲你顯然還有更多的代碼沒有顯示出來,所以你可能需要適當地調整它。此代碼正在全部工作1類