Olá, estou com algumas duvidas sobre como exportar uma jTable para Excel. Já li alguns post e cheguei no código abaixo, porem, não esta dando certo, algum poderia apontar o meu erro por favor?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc = new JFileChooser();
UtilitarioDAO u = new UtilitarioDAO();
int option = fc.showSaveDialog(jtRelatorio);
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(".xls")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xls";
}
try {
u.toExcel(jtRelatorio, new File(file)); // da erro aqui
} catch (IOException ex) {
// Logger.getLogger(formRdi.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(null, ex);
}
}
}
public void toExcel(JTable table, File file) throws IOException {
TableModel model = table.getModel();
FileWriter excel = new FileWriter(file);
for (int i = 0; i < model.getColumnCount(); i++) {
excel.write(model.getColumnName(i) + "\t");
}
excel.write("\n");
for (int i = 0; i < model.getRowCount(); i++) {
for (int j = 0; j < model.getColumnCount(); j++) {
excel.write(model.getValueAt(i, j).toString() + "\t");
}
excel.write("\n");
}
excel.close();
System.out.println("write out to: " + file);
}
Mano, eu vou te passar o código todo porquê fiquei séculos procurando algo que funcionasse, tive que entrar em vários sites pra ir juntando código:
try {
Thread t = new Thread() {
@Override
public void run() {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet xt = workbook.createSheet(); //Cria a pasta, eu não manjo muito de excel, mas é aquela coisa que fica lá no rodapé.
XSSFRow xr = xt.createRow(0); //Cria a linha
//Cria as colunas, Cell Value é nome da coluna que vai aparecer lá para o usuário (no excel)
xr.createCell(0).setCellValue("Nome");
xr.createCell(1).setCellValue("Bloco");
xr.createCell(2).setCellValue("Apto");
xr.createCell(3).setCellValue("Telefone 1");
xr.createCell(4).setCellValue("Telefone 2");
xr.createCell(5).setCellValue("Marca");
xr.createCell(6).setCellValue("Modelo");
xr.createCell(7).setCellValue("Placa");
xr.createCell(8).setCellValue("Vaga");
//Aqui ele seta o tamanho da coluna, em largura.
xt.setColumnWidth(0, (50 * 200));
xt.setColumnWidth(3, (50 * 90));
xt.setColumnWidth(4, (50 * 90));
xt.setColumnWidth(5, (50 * 90));
xt.setColumnWidth(6, (50 * 100));
xt.setColumnWidth(7, (50 * 65));
jProgressBar1.setMaximum(tabela.getRowCount()); // Aqui é o JProgressBar, uso ele + for pra dar a aparência que o software tá lendo as linhas da tabela.
XSSFRow xrs;
Rectangle rect;
//Aqui ele percorre a tabela e ficando passando linha por linha, pra dar a impressão que tá lendo
for (int i = 0; i < tabela.getRowCount(); i++) {
rect = tabela.getCellRect(i, 0, true);
try {
tabela.scrollRectToVisible(rect);
} catch (java.lang.ClassCastException e) {
}
tabela.setRowSelectionInterval(i, i);
jProgressBar1.setValue((i + 1));
xrs = xt.createRow((i + 1));
//Aqui ele pega o valor que tem nas colunas, óbviamente começa do Zero (0), mas eu não queria a coluna 0 porquê era o ID, e como pra o cliente final isso não faria diferença, eu ocultei.
xrs.createCell(0).setCellValue(tabela.getValueAt(i, 1).toString());
xrs.createCell(1).setCellValue(tabela.getValueAt(i, 2).toString());
xrs.createCell(2).setCellValue(tabela.getValueAt(i, 3).toString());
xrs.createCell(3).setCellValue(tabela.getValueAt(i, 4).toString());
xrs.createCell(4).setCellValue(tabela.getValueAt(i, 5).toString());
xrs.createCell(5).setCellValue(tabela.getValueAt(i, 6).toString());
xrs.createCell(6).setCellValue(tabela.getValueAt(i, 7).toString());
xrs.createCell(7).setCellValue(tabela.getValueAt(i, 8).toString());
xrs.createCell(8).setCellValue(tabela.getValueAt(i, 9).toString());
}
//As configurações do jProgressBar
jProgressBar1.setStringPainted(true); //String Painted é se vai ter algo escrito dentro dela, por exemplo: 10%
jProgressBar1.setValue(0); //Valor Inicial
jProgressBar1.setString("Abrindo Excel..."); //Essa string vai aparecer quando finalizar a leitura e pra o usuário ficar sabendo que vai acontecer algo, ao invés e abrir um jOption eu coloquei essa string.
//Aqui ele salva o arquivo.
try {
workbook.write(new FileOutputStream(new File(caminho + "//Morador.xlsx")));
Desktop.getDesktop().open(new File(caminho + "//Morador.xlsx"));
jProgressBar1.setString("");
} catch (IOException ex) {
}
}
};
t.start();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}