JTable 의 data(Row) 복사하는 법 - Excel
JTable 에서 선택한 Row 의 값을 복사하여 Excel 에 붙여넣기를 해보자
필요한 클래스는 StringBuffer, StringSelection, Clipboard 이다
우선 JTable 을 table 로 이미 생성해둔 상태이다
1. StringBuffer 객체를 생성한다 : 복사할 대상을 저장
StringBuffer sbf = new StringBuffer();
2. 선택한 table 의 row, column 수를 구한다 : 반복문에 사용할 예정
int numCols = table.getSelectedColumnCount();
int numRows = table.getSelectedRowCount();
3. 선택한 Cell 의 index 를 구한다 : 반복문에 사용할 예정
int colsSelected = table.getSelectedColums();
int rowsSelected = table.getSelectedRows();
4. cell 의 값을 가져와 sbf 에 저장한다
for(int i = 0; i < numrows; i++) {
for(int j = 0; j < numcols; j++) {
sbf.append(table.getValueAt(rowsSelected[i], j));
if(j < numcols - 1) {
sbf.append("\t"); // 다음 열에 삽입
} else {
sbf.append("\n"); // 다음 행에 삽입
}
}
}
5. StringSelection 클래스를 사용하여 Clipboard 에 저장한다
StringSelection entry = new StringSelection(sbf.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(entry, entry);
클립보드에 복사가 되었고 Excel 에서 붙여넣기를 한 모습이다
전체코드
StringBuffer sbf = new StringBuffer();
int numcols = table.getColumnCount();
int numrows = table.getSelectedRowCount();
int[] colsSelected = table.getSelectedColumns();
int[] rowsSelected = table.getSelectedRows();
for(int i = 0; i < numrows; i++) {
for(int j = 0; j < numcols; j++) {
sbf.append(table.getValueAt(rowsSelected[i], colsSelected[j]));
if(j < numcols - 1) {
sbf.append("\t");
} else {
sbf.append("\n");
}
}
}
StringSelection entry = new StringSelection(sbf.toString());
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents( entry, this);
Java Tip 77: Enable copy and paste functionality between Swing's JTables and Excel
JTables and Excel charts are commonly used to display data in a grid or table. Often, the data that the user wishes to enter into a JTable already exists in Excel spreadsheets. The Excel format is used for export-import functionality by software other than
www.infoworld.com
위 사이트를 참고하였으며 자세한 내용이 쓰여있다