简体   繁体   English

如何获取JTable中所有行的值并使用定界符和换行符将它们拆分?

[英]How to get values of all rows in JTable and split them with delimiters and newline?

Say I had a table like this: 说我有一张这样的桌子:

|ID|Name|Work|Age|
|31|John|IT  |31 |
|32|Jane|IT  |22 |

And I wanted to convert the values in the cell to string with delimiters(,) and newline like this: 我想使用delimiters(,)和换行符将单元格中的值转换为字符串,如下所示:

31,John,IT ,31 
32,Jane,IT ,22 

What code would I need to punch in in order for this to happen? 我需要打入什么代码才能做到这一点?

The following method convert a JTable in CSV String 以下方法将JTable转换为CSV字符串

public static String exportToCSV(JTable tableToExport) {
    StringBuilder stringBuilder = new StringBuilder();
    TableModel model = tableToExport.getModel();

    for (int i = 0; i < model.getRowCount(); i++) {
        for (int j = 0; j < model.getColumnCount(); j++) {
            stringBuilder.append(model.getValueAt(i, j).toString()).append(",");
        }
        stringBuilder.append("\n");
    }

    return stringBuilder.toString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM