2009-09-14 2 views
2

CSV 데이터를 가지고 있습니다. 실제로 값은 탭 문자로 구분되지만 ;을 구분 기호로 사용할 수 있습니다. 데이터는 String 개체에 저장됩니다.CSV 데이터로 JTable을 손쉽게 채울 수 있습니다.

String 개체를 읽고 구문 분석하여 수동으로 수행하지 않고이 데이터로 JTable을 만드는 간단한 방법이 있습니까?

(참고 : 내 프로젝트는 자바 1.4을 사용하고 있지만, 자바 1.5이 필요 해결책을 가지고 있다면, 어쨌든 행복 할 것)

답변

2

TableModelExtTextLoader에서 swinglabs으로 연락 드리겠습니다. 탭과 쉼표로 구분 된 텍스트를 모두 지원합니다.

+1

OpenCSV 또한 그것을 얻는 쉬운 방법입니다 : http://stackoverflow.com/questions/10466079/import-csv-to-jtable – Benj

1

를 CSV가없는 - 어딘가가>의 TableModel 방법 당신 불행히도 모델을 채울 코드를 작성해야합니다.

+0

내가 무엇을 찾고있어 그 다음은 자바 1.5에서 스캐너 클래스를 사용하는 예입니다 거기에 더 쉬운 방법이 있었 ... – romaintaz

2

외부 라이브러리가 없어도이 작업을 수행하기 쉽습니다. 나는이 테이블을 작성하기위한 매뉴얼 코드를 구현 한 ),하지만 난 경우보고 싶어;

import java.io.*; 
import java.net.URL; 
import java.util.Scanner; 
import javax.swing.*; 
import javax.swing.table.DefaultTableCellRenderer; 
import javax.swing.table.DefaultTableModel; 

public class CSVTable extends JFrame { 
    JTable table; 
    DefaultTableModel model; 
    JButton closeButton, webButton; 
    /** 
    * Takes data from a CSV file and places it into a table for display. 
    * @param source - a reference to the file where the CSV data is located. 
    */ 
    public CSVTable(String title, String source) { 
    super(title); 
    table = new JTable(); 
    JScrollPane scroll = new JScrollPane(table); 
    String[] colNames = { "LastName", "FirstName", "Email Address", "Dept."}; 
    model = new DefaultTableModel(colNames, 0); 
    InputStream is; 
    try { 
     if(source.indexOf("http")==0) { 
      URL facultyURL = new URL(source); 
      is = facultyURL.openStream(); 
     } 
     else { //local file? 
      File f = new File(source); 
      is = new FileInputStream(f); 
     } 
     insertData(is); 
     //table.getColumnModel().getColumn(0).setCellRenderer(new CustomCellRenderer()); 
    } 
    catch(IOException ioe) { 
     JOptionPane.showMessageDialog(this, ioe, "Error reading data", JOptionPane.ERROR_MESSAGE); 
    } 

    JPanel buttonPanel = new JPanel(); 
    closeButton = new JButton("Close"); 
    webButton = new JButton("Proctinator.com"); 
    buttonPanel.add(closeButton); 
    buttonPanel.add(new JLabel(" You can download this file from our site: ")); 
    buttonPanel.add(webButton); 

    JPanel notesPanel = new JPanel(); 
    JLabel note1 = new JLabel(" Make sure that your list is formatted exactly as shown below, including the *markers between categories "); 
    JLabel note2 = new JLabel(" Be sure to place each faculty member into the correct category: *Teacher, *Subs, *TeacherAids, *TeacherAssistants "); 
    JLabel note3 = new JLabel(" Note that the your faculty list must be a plain text file: Export to either CSV or tab delimited format."); 
    BoxLayout layout = new BoxLayout(notesPanel, BoxLayout.Y_AXIS); 
    notesPanel.setLayout(layout); 
    notesPanel.add(note1); 
    notesPanel.add(note2); 
    notesPanel.add(note3);  
    getContentPane().add(notesPanel, BorderLayout.NORTH); 
    getContentPane().add(scroll, BorderLayout.CENTER); 
    getContentPane().add(buttonPanel, BorderLayout.SOUTH); 
    pack(); 
} 

/** 
* Places the data from the specified stream into this table for display. The data from the file must be in CSV format 
* @param is - an input stream which could be from a file or a network connection or URL. 
*/ 
void insertData(InputStream is) { 
    Scanner scan = new Scanner(is); 
    String[] array; 
    while (scan.hasNextLine()) { 
     String line = scan.nextLine(); 
     if(line.indexOf(",")>-1) 
      array = line.split(","); 
     else 
      array = line.split("\t"); 
     Object[] data = new Object[array.length]; 
     for (int i = 0; i < array.length; i++) 
      data[i] = array[i]; 

     model.addRow(data); 
    } 
    table.setModel(model); 
} 

public static void main(String args[]) { 
    CSVTable frame = new CSVTable("Faculty List Example","http://proctinator.com/help/faculty.csv"); 
    frame.setVisible(true); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} 

}

+0

답장을 보내 주셔서 감사합니다, 제 질문은 휠을 재발견하지 않고 *이를 수행하는 방법이었습니다. CSV 파일에서 데이터를 추출하는 것은 쉽습니다, 그리고 JTable에 그것들을 삽입하는 것 ... – romaintaz

관련 문제