Apache POI - Excel导入,将新工作表中的数据插入到列中

时间:2017-05-19 12:03:35

标签: java excel apache

我来这里是为了在Netbeans的java项目中寻求帮助。

我使用Apache POI导入/导出Excel数据。为了让您了解我的应用程序中的问题,我将向您展示调试的打印。

print1

在打印中,您可以看到2张纸。第一个标题" aiai"以及该表中的数据。

我的问题是:我如何插入来自" aiai2"的数据?这是我的excel文件中的第二张表,位于标题下方的正确位置" aiai2"

换句话说,我想垂直分开纸张。

下面,我将展示我的代码:

Workbook wb;

public String Importar(File archivo, JTable tablaD) {
    String answer = "Unable to import";
    DefaultTableModel modeloT = new DefaultTableModel();
    tablaD.setModel(modeloT);
    tablaD.getModel();
    tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    try {
        wb = WorkbookFactory.create(new FileInputStream(archivo));
        int nsheets = wb.getNumberOfSheets();

        for (int i = 0; i < nsheets; i++) {

            Sheet sheet = wb.getSheetAt(i);
            Iterator filaIterator = sheet.rowIterator();

            int rownum = -1;
            while (filaIterator.hasNext()) {
                rownum++;
                Row fila = (Row) filaIterator.next();
                /*if (i > 0) {//se o nr da ficha atual for maior que 0, começa a escrever as linhas apartir da row 0 da tabela
                    modeloT.moveRow(modeloT.getRowCount() -1, modeloT.getRowCount() - 1, 0);
                }*/
                Iterator columnaIterator = fila.cellIterator();
                Object[] listaColumna = new Object[1000];
                int columnnum = -1;
                while (columnaIterator.hasNext()) {
                    columnnum++;
                    Cell celda = (Cell) columnaIterator.next();

                    if (rownum == 0) {
                        modeloT.addColumn(celda.getStringCellValue());
                    } else {
                        if (celda != null) {
                            switch (celda.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    listaColumna[columnnum] = (int) Math.round(celda.getNumericCellValue());
                                    break;
                                case Cell.CELL_TYPE_STRING:
                                    listaColumna[columnnum] = celda.getStringCellValue();
                                    break;
                                case Cell.CELL_TYPE_BOOLEAN:
                                    listaColumna[columnnum] = celda.getBooleanCellValue();
                                    break;
                                default:
                                    listaColumna[columnnum] = celda.getDateCellValue();
                                    break;
                            }//end switch case
                            System.out.println("Column:" + columnnum + " Row:" + rownum + " value:" + celda + ".");

                        }
                    }
                }//end while column Iterator
                if (rownum != 0) {
                    modeloT.addRow(listaColumna);
                }
            }//end while row iterator
        }//end for
        answer = "Imported with success";

    } catch (IOException | InvalidFormatException | EncryptedDocumentException e) {
        System.err.println(e.getMessage());
    }
    return answer;
}

public String Exportar(File archivo, JTable tablaD) {
    String answer = "Unable to export";
    int numFila = tablaD.getRowCount(), numColumna = tablaD.getColumnCount();
    if (archivo.getName().endsWith("xls")) {
        wb = new HSSFWorkbook();
    } else {
        wb = new XSSFWorkbook();
    }
    Sheet hoja = wb.createSheet("Default");

    try {
        for (int i = -1; i < numFila; i++) {
            Row fila = hoja.createRow(i + 1);
            for (int j = 0; j < numColumna; j++) {
                Cell celda = fila.createCell(j);
                if (i == -1) {
                    celda.setCellValue(String.valueOf(tablaD.getColumnName(j)));
                } else {
                    celda.setCellValue(String.valueOf(tablaD.getValueAt(i, j)));
                }
                wb.write(new FileOutputStream(archivo));
            }
        }
        answer = "Exported with success";
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return answer;
}

1 个答案:

答案 0 :(得分:0)

据我了解你的问题,我假设你想为每张纸创建一个单独的表,一张低于另一张。在这种情况下,您需要在每次阅读新工作表时创建一个新表。如果您只使用一个表,则只能获得一个表。

试试这个:

创建一个新方法Importar,该方法采用新表和Sheet参数

public String Importar(JTable tablaD, Sheet sheet) {
    String answer = "Unable to import";
    DefaultTableModel modeloT = new DefaultTableModel();
    tablaD.setModel(modeloT);
    tablaD.getModel();
    tablaD.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);


    try {


            Iterator filaIterator = sheet.rowIterator();

            int rownum = -1;
            ....
            ....

所以调用方法是:

try {
    Workbook wb = WorkbookFactory.create(new FileInputStream(archivo));
    int nsheets = wb.getNumberOfSheets();

    for (int i = 0; i < nsheets; i++) {
           //You have to make sure your JTable gets rendered.
           JTable tablaD = new JTable();
           Importar( tablaD, wb.getSheetAt(i) );
    }
} catch ( Exception e ) {
      e.printStackTrace();
 }

重要的一点是,每次拨打Importar之前,您的新表都需要呈现或添加到框架中