apache poi: salvando jtable em um arquivo
Eu comecei recentemente a trabalhar com java e estou enfrentando alguns problemas com a biblioteca apache poi quando eu preciso criar um arquivo de excel a partir de um jTable.
Eu li muitos tópicos e criei algum código que simplesmente não funciona (mesmo que seja algo muito fácil e tenha muitos exemplos, o que me faz parecer ainda mais burro) e eu estava esperando que alguém pudesse me ajudar.
Então, aqui estão as perguntas:
a) Por que o loop for, que deve gravar o arquivo do Excel, não preenche todas as células? (a única linha com dados no arquivo Excel é a sexta, o que também me faz pensar por que conta os itens nulos no modelo de tabela para os métodos getRowCount / Column. Também sei que está imprimindo uma String personalizada e não a tabela em si, mas salve isso para o ponto b)
b) Como devo usar os itens do modelo jtable para preencher o arquivo do Excel, pois ao criar a tabela eu tive que escolher o objeto como tipo de linha? (Eu também estou tendo problemas com o tipo de objeto especialmente, contanto que seja um inteiro String || não há nenhum problema, mas a tabela é suposto ter uma mistura de ambos que não parece funcionar quando você tenta use o método setCellValue () com algo diferente do string inteiro || integer..or pelo menos eu não consegui fazer funcionar)
c) Digamos que eu queira mais tarde preencher o jtable do arquivo que eu criei anteriormente, eu teria simplesmente que usar a solução para apontar b) (o inverso disso é) depois de ler o arquivo com a classe bufferedReader?
Aviso Legal: a primeira parte do código é gerada automaticamente pelo netbeans, como você provavelmente pode dizer, a parte hssf que eu criei é no final, mas eu pensei que você poderia querer ver a coisa toda, desculpe se parece meio confuso.
Aqui está o código:
package poitest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
public class POITestFrame extends javax.swing.JFrame {
/**
* Creates new form POITestFrame
*/
public POITestFrame() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
excelButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
excelButton.setText("ESPORTA!");
excelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
excelButtonActionPerformed(evt);
}
});
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"Boolean", "Integer", "String", "Array"},
{"x*y", "x+y", "x/y", "x-y"},
{"32", "43", "12", "24"},
{"casa", "cantiere", "museo", "acquario"},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 320, Short.MAX_VALUE)
.addComponent(excelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 91, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(excelButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void excelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_excelButtonActionPerformed
try {
PoiWriter(jTable1);
} catch (FileNotFoundException ex) {
Logger.getLogger(POITestFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(POITestFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_excelButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*
* Set the Nimbus look and feel
*/
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(POITestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new POITestFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton excelButton;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration//GEN-END:variables
private void PoiWriter(JTable jTable1) throws FileNotFoundException, IOException {
TableModel model = jTable1.getModel();
// create a workbook
Workbook wb = new HSSFWorkbook(); // xls file
// create a new sheet
Sheet sheet = wb.createSheet("Foglio di Prova!");
// declare a row object reference
Row r = null;
// declare a cell object reference
Cell c = null;
// create a new file
FileOutputStream fos;
fos = new FileOutputStream("File di Prova.xls");
// create a sheet table rows
int rownum;
for (rownum = (short) 0; rownum < model.getRowCount(); rownum++) {
// create a row
r = sheet.createRow(rownum);
}
for (short cellnum = (short) 0; cellnum < model.getRowCount(); cellnum ++) {
// create a numeric cell
c = r.createCell(cellnum);
// populate table with custom objects
for(int i=0; i < model.getRowCount();i++){
for(int j=0;j < model.getColumnCount();j++){
String aplala = "blabla";
c.setCellValue(aplala);
}
}
}
wb.write(fos);
fos.close();
}
}
PS: Se você está se perguntando por que eu construí a tabela com tipos de objeto: este não é o projeto que estou trabalhando, eu fiz este trecho para testar o hssf como o Excel resultante é bastante editável, mas as coisas não parecem vá bem.
PPS: Eu tentei trabalhar com a classe tokenizer também, mas eu não tenho certeza se você pode editar o arquivo excel resultante, tanto quanto com poi lib.
PPPS: Esta é a minha primeira tentativa com java, por favor, não seja tão grosseiro!
Espero que as perguntas tenham sido suficientemente claras e agradeço antecipadamente que estou tentando melhorar a programação: P
EDIT: depois de um dia de prática é isso que eu vim com o que parece funcionar com a biblioteca apache poi, obrigado pela ajuda pessoal deu bons ponteiros!
int rowNum;
int colNum;
int tempRows;
int rowCount = model.getRowCount();
int columnCount = model.getColumnCount();
// create the headers
for (colNum = 0; colNum < columnCount; colNum++) {
if (colNum == 0) {
r = sheet.createRow(0);
}
c = r.createCell(colNum);
c.setCellValue(model.getColumnName(colNum));
}
for (rowNum = 0; rowNum < rowCount; rowNum++) {
// create rows + 1 (to account for the headers)
tempRows = rowNum + 1;
r = sheet.createRow(tempRows);
for (short cellnum = 0; cellnum < columnCount; cellnum ++) {
// create cells
c = r.createCell(cellnum);
// add values from table
c.setCellValue(model.getValueAt(rowNum, cellnum).toString());
}
}
Sinta-se livre para comentar se você acha que o código pode ser melhorado, sugestões são sempre bem-vindas, especialmente para novatos como eu;)
Mais uma vez, obrigado pelas dicas, eles realmente fizeram o truque ^^