gpt4 book ai didi

Java从csv读取并显示在jTable上

转载 作者:行者123 更新时间:2023-12-01 11:10:57 27 4
gpt4 key购买 nike

我一直坚持从 csv 中读回,我成功地创建了 csv。我面临的问题是我无法获得有关如何获取从 csv 返回到 jTable 的值的线索。除了 public void fromCsv

之外,我没有遇到任何其他问题
  class FCMS extends JFrame{
String header[] = {"Firstname","Lastname","FCMS ID","Email"};
String data[][];
DefaultTableModel model = new DefaultTableModel(data, header);
JTable table = new JTable(model);
JPanel pane = new JPanel();
JPanel pane_input = new JPanel();
JLabel lbl_firstname = new JLabel(" Firstname");
JLabel lbl_lastname = new JLabel(" Lastname");
JLabel lbl_id = new JLabel(" FCMS ID");
JLabel lbl_email = new JLabel(" Email");
JTextField txt_firstname = new JTextField(10);
JTextField txt_lastname = new JTextField(10);
JTextField txt_id = new JTextField(10);
JTextField txt_email = new JTextField(10);
JButton btn_add = new JButton("Add Entry");
JButton btn_Csv = new JButton("Export to Csv");
JButton btn_load = new JButton("Load From Csv");

public FCMS(){
setSize(200,200);
setPreferredSize(new Dimension(350,300));
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(true);
setTitle("Flight Crew Management System");

btn_add.setMnemonic(KeyEvent.VK_A);
btn_Csv.setMnemonic(KeyEvent.VK_E);
btn_load.setMnemonic(KeyEvent.VK_L);

pane_input.setLayout(new GridLayout(0,2));
pane_input.add(lbl_firstname);
pane_input.add(txt_firstname);
pane_input.add(lbl_lastname);
pane_input.add(txt_lastname);
pane_input.add(lbl_id);
pane_input.add(txt_id);
pane_input.add(lbl_email);
pane_input.add(txt_email);
pane_input.add(btn_add);
pane_input.add(btn_Csv);
pane_input.add(btn_load);

pane.setLayout(new BorderLayout());
pane.add(pane_input, BorderLayout.NORTH);
pane.add(new JScrollPane(table), BorderLayout.CENTER);

add(pane);
pack();
setVisible(true);

btn_add.addActionListener(new AksyonListener());
btn_Csv.addActionListener(new AksyonListener());
btn_load.addActionListener(new AksyonListener());
txt_email.addActionListener(new AksyonListener());
}

public void toCsv(JTable table, File file){
try{
TableModel model = table.getModel();
FileWriter Csv = new FileWriter(file);


for(int i = 0; i < model.getColumnCount(); i++){
Csv.write(model.getColumnName(i) + ",");
}

Csv.write("\n");

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

Csv.close();
}catch(IOException e){ System.out.println(e); }
}

public void fromCsv(File file){

BufferedReader fileReader = null;
model.setRowCount(0);

try{

//Create the file reader
fileReader = new BufferedReader(new FileReader(file));

//Read the CSV file header to skip it
fileReader.readLine();

int fn = 0;
int ln = 1;
int id = 2;
int email = 3;


String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {

// }
}


/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/

fileReader.close();

}catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
}

}

public static void main(String[] args){
new FCMS();
}

class AksyonListener implements ActionListener{
public void actionPerformed(ActionEvent e){
if(e.getSource() == btn_add || e.getSource() == txt_email){
String fn = txt_firstname.getText();
String ln = txt_lastname.getText();
String id = txt_id.getText();
String mail = txt_email.getText();

txt_firstname.setText("");
txt_lastname.setText("");
txt_id.setText("");
txt_email.setText("");
txt_firstname.requestFocus();

model.insertRow(model.getRowCount(), new Object[]{fn, ln, id, mail});
}
else if(e.getSource() == btn_Csv){

JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(FCMS.this);

if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();

int len = filename.length();
String ext = "";
String file = "";

if(len > 4){
ext = filename.substring(len-4, len);
}

if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}
toCsv(table, new File(file));
}
}
else if(e.getSource() == btn_load){

JFileChooser fc = new JFileChooser();
int option = fc.showOpenDialog(FCMS.this);

if(option == JFileChooser.APPROVE_OPTION){
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();

int len = filename.length();
String ext = "";
String file = "";

if(len > 4){
ext = filename.substring(len-4, len);
}

if(ext.equals(".csv")){
file = path + "\\" + filename;
}else{
file = path + "\\" + filename + ".csv";
}

fromCsv(new File(file));

}
}
}
}
}

问题已解决:

try{

//Create the file reader
fileReader = new BufferedReader(new FileReader(file));

//Read the CSV file header to skip it
fileReader.readLine();

int fn = 0;
int ln = 1;
int id = 2;
int email = 3;


String line="";
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
// if (tokens.length > 0) {

// }
}


/* for(int i=0; i< tokens.length; i++) {
for(int j=0; j < tokens.length; j++) {
//Csv.read(model.getValueAt(i,j).toString()+"\t");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});
}
// Csv.read("\n");
}*/

fileReader.close();

}

最佳答案

String[] tokens = line.split(",");

上面是将一行数据拆分为一个数组的位置,因此上面是您需要从数组中获取数据并将其添加到 TableModel 的位置。

所以你的代码应该是:

String[] tokens = line.split(",");
model.insertRow(model.getRowCount(), new Object[]{Long.parseLong(tokens[fn]), tokens[ln], tokens[id], tokens[email]});

那么就不需要第二次循环了。

但是,上面的代码只是将数据追加到现有的“模型”中,因此您可能还需要清除模型中的所有数据。您可以通过添加以下内容来做到这一点:

model.setRowCount(0);

循环之前。

关于Java从csv读取并显示在jTable上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32380743/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com