繁体   English   中英

从JTable到Excel

[英]From JTable to Excel

我正在尝试将JTable导出到Excel文件。 为此,请使用apache POI-SS和apache POI-XSSF。 首先,我使用sax解析器解析xml文件,并将其trnsform转换为JTable,然后单击“导出”按钮,我想将JTable导出为ex​​cel。我创建了2个类,第一个类解析xml文件并创建一个Jtable和第二个用于Excel导出。

我的问题是excel文件,它仅包含2个元素:第一行包含200000,第二行包含100000 ...我试图找到问题所在,但徒劳无功。

这是“ JTable_create”类:

package jtable_excel11;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class JTable_create {

public static Vector<Vector> rowData = new Vector<Vector>();
public static Vector<String> rowOne = new Vector<String>();
public static Vector<String> columnNames = new Vector<String>();
public static void main(String[] args) {

try {

SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();

DefaultHandler handler;
handler = new DefaultHandler() {
boolean bstaff = false;
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
private int i;

public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {

System.out.println("Start Element :" + qName);

if (qName.equalsIgnoreCase("staff"))
{
rowOne = new Vector<String>();
bstaff = true;
}

if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}

if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}

if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}

if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}

}

public void endElement(String uri, String localName,
String qName) throws SAXException {

System.out.println("End Element :" + qName);
if ("staff".equals(qName)){
rowData.addElement(rowOne);
System.out.println("pffffffffff");
};

}



@Override
public void characters(char ch[], int start, int length)  {

if (bfname) {
String s = new String(ch, start, length);
rowOne.addElement(s);
System.out.println("First Name : " + new String(ch, start, length));

bfname = false;

}

if (blname) {
rowOne.addElement (new String(ch, start, length));
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;

}

if (bnname) {
rowOne.addElement (new String(ch, start, length));
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;

}

if (bsalary) {
rowOne.addElement (new String(ch, start, length));
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;

}

System.out.println("longueur" + rowOne.size());
}
};

saxParser.parse("file.xml", handler);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
columnNames.addElement("firstname");
columnNames.addElement("lastname");
columnNames.addElement("nickname");
columnNames.addElement("salary");

DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
final JTable table = new JTable(model);


JScrollPane scrollPane = new JScrollPane(table);

JButton export = new JButton("Export");
export.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
try {
Escel1 exp = new Escel1();
exp.exportTable(table, new File("C:\\Documents and              Settings\\Adm\\Bureau\\result.xlsx"));
} catch (IOException ex)  {
System.out.println(ex.getMessage());
ex.printStackTrace();
}
}
});

frame.getContentPane().add("South", export);
frame.pack();
frame.setVisible(true);

frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
System.out.println("Fini!");

} catch (Exception e) {
e.printStackTrace();
}

}

}

第二类称为“ Excel1”,其内容如下:

package jtable_excel11;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.swing.JTable;
import javax.swing.table.TableModel;


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class Excel1 {



public Excel1() {}

public void exportTable(JTable table, File file) throws IOException {


System.out.println(" c bon !");

XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Sample sheet");

System.out.println(" workbook crée");
TableModel model= table.getModel();
HashMap<String, Object[]> data = new HashMap<String, Object[]>();

for(int i=0; i<model.getRowCount(); i++){
for(int j=0; j< model.getColumnCount(); j++){


data.put(i+"",new Object[]{model.getValueAt(i,j).toString()+"\t"});
System.out.println(model.getValueAt(i,j));
System.out.println(i);
System.out.println(j);


}
//data.put("\n");


}

Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}

try {
FileOutputStream out = new FileOutputStream(file);
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");

}  catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

这是我的Xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<company>
<staff >
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff >
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>

在excel文件中,我只有2行,分别包含200000和100000。

知道我该如何解决吗? 提前致谢

我认为您可以通过将JTable导出为简单的filtype来导出它:“。csv” Excel可以简化它。

一个简单的例子是

kevin,johnson,49
julia,roberts,56

我认为您正在使用JTable作为表而不是树(XML是树的类型)

祝好运

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM