我最近开始使用 java,当我需要从 jTable 创建一个 excel 文件时,我遇到了 apache poi 库的一些问题。
我已经阅读了很多线程并提出了一些不起作用的代码(即使这是非常简单的东西并且有很多示例,这让我看起来更加愚蠢),我希望有人可以帮助我。
所以这里有问题:
a)为什么应该编写excel文件的for循环不填充每个单元格?(excel文件中唯一有数据的行是第六行,这也让我想知道为什么它会为getRowCount / Column方法计算表模型中的空项目..我也知道它正在打印自定义字符串而不是表格本身,但将其保存到点 b)
b)我应该如何使用 jtable 模型项来填充 excel 文件,因为在创建表时我必须选择对象作为行类型?(特别是我也遇到了对象类型的问题,只要它是一个字符串||整数就没有问题,但是表应该是两者的混合,当你尝试时这似乎不起作用使用与 String||integer 不同的 setCellValue() 方法..或者至少我无法使其工作)
c)假设我稍后想从我之前创建的文件中填充 jtable,在使用 bufferedReader 类读取文件后,我是否只需要使用 b) 点的解决方案(另一种方法是)?
免责声明:代码的第一部分是由 netbeans 自动生成的,你可能会说,我想出的 hssf 部分在最后,但我想你可能想看看整个事情,抱歉,如果它看起来有点乱.
这是代码:
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:如果您想知道为什么我用对象类型构建表:这不是我正在使用的项目,我制作了这个片段来测试 hssf,因为生成的 excel 是非常可编辑的,但事情似乎没有顺利。
PPS:我也尝试使用 tokenizer 类,但我不确定您是否可以像使用 poi lib 那样编辑生成的 excel 文件。
PPPS:这是我第一次尝试使用java,所以请不要太粗暴!
我希望问题足够清楚,并提前感谢,我确实在努力提高编程能力:P
编辑:经过一天的练习,这就是我想出的似乎可以与 apache poi 库一起使用的方法,感谢它提供了良好指示的帮助人员!
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());
}
}
如果您认为代码可以改进,请随时发表评论,欢迎提出建议,尤其是像我这样的新手;)
再次感谢您的提示,他们真的成功了^^