Saving JTable as text file

后端 未结 4 1252
星月不相逢
星月不相逢 2021-01-03 17:14

I am saving a .txt and .doc file containing the data from my JTable. At the minute when it saves it lays the text out like its in a table, but due to different lengths of da

4条回答
  •  日久生厌
    2021-01-03 17:59

    A minimal example I made is provided below. I gives the following form of output:

    First Name: Kathy
    Last Name: Smith
    Sport: Snowboarding
    # of Years: 5

    First Name: John
    Last Name: Doe
    Sport: Rowing
    # of Years: 2

            String[] columnNames = {"First Name", "Last Name","Sport","# of Years"};
    
        Object[][] data = {
                {"Kathy", "Smith", "Snowboarding", "5"},
                {"John", "Doe", "Rowing", "2"},
                {"Sue", "Black", "Knitting", "8"},
                {"Jane", "White", "Speed reading", "10"},
                {"Joe", "Brown", "Pool", "20"}
        };
    
        JTable table = new JTable(data, columnNames);
    
        for(int row = 0; row < table.getRowCount(); row++) {
    
            for(int column = 0; column < table.getColumnCount(); column++) {
                System.out.print(table.getColumnName(column) + ": ");
                System.out.println(table.getValueAt(row, column));
            }
            System.out.println(""); // Add line space
        }
    

提交回复
热议问题