如何将数据从JTable导出到CSV [英] How to export data from JTable to CSV
问题描述
我在启动一些代码从JTable中提取值时遇到问题,这样我最终可以将它们称为CSV文件,以便在Excel上查看。目前我使用以下代码创建了一个JTable:
I am just having problems starting a bit of code to extract values from JTable so that I can eventually say them as a CSV file for viewing on Excel. Currently I have a JTable created using the following code:
package com.alpha;
import javax.swing.*;
import java.awt.*;
public class JTableComponent{
public static void main(String[] args)
{
new JTableComponent();
}
public JTableComponent(){
JFrame frame = new JFrame("Whiteboard Test");
JPanel panel = new JPanel();
String data[][] = {{"Company A","1000","1"},{"Company B","2000","2"},
{"Company C","3000","3"},{"Company D","4000","4"}};
String col[] = {"Company Name","Shares","Price"};
JTable table = new JTable(data,col);
panel.add(table,BorderLayout.CENTER);
frame.add(panel);
frame.setSize(300,200);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
我已经开始了一个新的课程,无论什么时候都会被调用按下导出到CSV按钮。我将在稍后阶段实现按钮监听器等,现在我想要一些关于如何创建for look的指针,这些指针将遍历列和行以查找其中包含的值。请注意,JTable是可扩展的,当前的JTable仅用于测试目的。我知道有一些API可用,比如Apache,但是我不想使用它们。
I have started a new class that will be called whenever the "Export to CSV" button is pressed. I will implement the button listeners etc at a later stage, right now I would like a few pointers on how to create the for look that will go through the columns and rows looking for the values contained in them. Just a note, the JTable will be scalable, the current JTable is just for test purposes. I know there are APIs available such as the Apache one however I would prefer not to use them.
package com.alpha;
public class Exporter extends JTableComponent
{
public changeToCSV(){
}
public changeToCSV()
{
for(int j = 0; j < table.getColumnCount(); j++) {
}
}
我无法确定构造函数应该接收的内容。非常感谢您的帮助!
I am having trouble deciding what the constructor should expect to receive. Many thanks for your help in advance!
推荐答案
我使用以下方法从JTable中提取数据为csv,希望这将是对某人有帮助
I used following method in to extract data as csv from JTable, hopefully this will be helpful to someone
public static boolean exportToCSV(JTable tableToExport,
String pathToExportTo) {
try {
TableModel model = tableToExport.getModel();
FileWriter csv = new FileWriter(new File(pathToExportTo));
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();
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
这篇关于如何将数据从JTable导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!