java 如何将数据从 JTable 导出到 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3709799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to export data from JTable to CSV
提问by Joey jie
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:
我只是在启动一些代码以从 JTable 中提取值时遇到问题,以便我最终可以将它们作为 CSV 文件在 Excel 上查看。目前我有一个使用以下代码创建的 JTable:
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);
}
}
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.
我已经开始了一个新类,只要按下“导出到 CSV”按钮就会调用它。我将在稍后阶段实现按钮侦听器等,现在我想要一些关于如何创建 for 外观的指针,该外观将遍历列和行以查找其中包含的值。请注意,JTable 将是可扩展的,当前的 JTable 仅用于测试目的。我知道有一些可用的 API,例如 Apache,但我不想使用它们。
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!
我在决定构造函数应该期望收到什么时遇到了麻烦。非常感谢您的帮助!
回答by Mr. Xymon
Maybe you want to consider using TSV (Tab-Separated Values) as an alternative to comma-separated value (CSV) format, which often causes difficulties because of the need to escape commas. Here's a simple java tutorial that implements a JTable then exports it to MS Excel file using TSV format: How To Export Records From JTable To MS Excel
也许您想考虑使用 TSV(制表符分隔值)作为逗号分隔值 (CSV) 格式的替代方案,由于需要转义逗号,这通常会导致困难。这是一个简单的 Java 教程,它实现了 JTable,然后使用 TSV 格式将其导出到 MS Excel 文件:How To Export Records From JTable To MS Excel
Below is the exported excel file (manually adjusted column widths)
下面是导出的excel文件(手动调整列宽)
回答by Zain Ali
I used following method in to extract data as csv from JTable, hopefully this will be helpful to someone
我使用以下方法从 JTable 中提取数据为 csv,希望这对某人有所帮助
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;
}
回答by Adamski
The Exporter class method definitions are invalid. You need to include return types in order for this code to compile (I presume this is what you mean when you mention about what the constructor should return).
导出器类方法定义无效。您需要包含返回类型才能编译此代码(我认为这就是您提到构造函数应返回的内容时的意思)。
For a simple implementation you could consider returning a String[][] which you could then translate into csv data in a doubly nested loop. I have implemented something in the past where I had a structure similar to:
对于一个简单的实现,您可以考虑返回一个 String[][] ,然后您可以在双重嵌套循环中将其转换为 csv 数据。我在过去实现了一些类似的结构:
ExportAction
|
|--> ExportDestination
|--> ExportFormatter
The ExportAction
is an implementation of javax.swing.Action
and is associated with the "Export to csv" button. It references two classes:
这ExportAction
是javax.swing.Action
“导出到 csv”按钮的一种实现并与“导出到 csv”按钮相关联。它引用了两个类:
ExportDestination
: The logical destination for the csv data. This interface offers a method createWriter() that is called by the action to create a "sink" which to squirt the csv data down. A concrete implementation ofExportDestination
is FileDestination, but I also implemented others such asClipboardDestination
.ExportFormatter
: Responsible for translating the table rows into csv data. I chose to do this one row at a time: TheExportAction
would iterate over each row to export callingexportFormatter.writeTableRow
and passing in the writer created from the export destination. This gave me the flexibility to decide which rows to export (e.g. those currently visible / currently selected / all rows).
ExportDestination
:csv 数据的逻辑目标。该接口提供了一个方法 createWriter() ,该方法被操作调用以创建一个“接收器”,将 csv 数据向下喷射。的具体实现ExportDestination
是 FileDestination,但我也实现了其他的,例如ClipboardDestination
.ExportFormatter
: 负责将表格行转换成csv数据。我选择一次执行这一行:ExportAction
将迭代每一行以导出调用exportFormatter.writeTableRow
并传入从导出目标创建的编写器。这使我可以灵活地决定要导出哪些行(例如,那些当前可见/当前选定/所有行)。
So in answer to your original question I didn't return anything from my various export methods. Instead, when the action was invoked I would prompt the user to select parameters (e.g. file name) which I would then set before invoking my export routine.
所以在回答你最初的问题时,我没有从我的各种导出方法中返回任何东西。相反,当操作被调用时,我会提示用户选择参数(例如文件名),然后我将在调用导出例程之前设置这些参数。
Hope that helps.
希望有帮助。
回答by James P.
Exporter could be made into a helper class. However, since it appears you want to export any JTable what you could do to make things simple would be to switch to a utility method.
Exporter 可以被做成一个辅助类。但是,既然您似乎想要导出任何 JTable,那么您可以做的事情就是切换到实用程序方法来使事情变得简单。
public class CSVExporterUtils{
public static void exportToCSV( JTable tableToExport, String pathToExportTo ){
// Pseudocode below
/*
Open file and test if valid path
Loop through each table line
Loop through each column
Get value at line, column
Add value to StringBuilder plus a comma
Write contents of StringBuilder to file
And add return using System.getProperty("line.separator")
End Loop
Close file
*/
}
}
You could then call this method as follows:
然后,您可以按如下方式调用此方法:
CSVExporterUtils.exportToCSV( myJTable, "c:/myExportedData.csv" );
CSVExporterUtils.exportToCSV( myJTable, "c:/myExportedData.csv" );