Do Merge of data to EXCEL Documents?

0

Good day, it happens that I need to make a functionality that modifies some fields that are defined in an excel document in JAVA just as I am doing it at the moment with word documents (.docx), the truth is that there is an API but I have no idea where to find it or how it works, the idea is to do the following, I will post the example of the Word because you want the same thing but in excel documents:

The WORD document, the template is made in the following way, for example:

Buen día <item2> <item3>, su número de solicitud es el <item1>, cuando la evaluemos se le informará

Datos del solicitante:

    Nombre: <item2>
    Apellido: <item3>
    Cargo: <item4>
    Institución: <item5>

In the program you run and say, make a proposal to send more games to your university, then we generated the request and we created the document and it would be:

Buen día Fabian Montoya, su número de solicitud es el 123456789, cuando la evaluemos se le informará

Datos del solicitante:

    Nombre: Fabian
    Apellido: Montoya
    Cargo: Estudiante
    Institución: Universidad Nacional

And that's it, the document is generated and given to download, that's how the word document works, now I need to be able to do the same but with document templates that are made in excel.

With the same structure, change that they are there for data that we handle from the program, I do not know if I make myself understood, I wait for their help, I have looked for two hours and I do not get anything.

    
asked by Fabian Montoya 04.11.2016 в 21:30
source

2 answers

0

I already did it, it was like that.

static String ruta1 = "D:/", document1 = "FOR_001_EXAMPLE", type1 = ".xlsx";
static String Documento = "", NewDocumento = "";

public static void XLSX(String Ubicacion) throws IOException {

        Ubicacion = Ubicacion.replace("\", "/"); //Convierto todos los \ en / para congruir en direcciones
        try {
            File Fil = new File(Ubicacion); //Se crea un archivo File
            FileInputStream file = new FileInputStream(Fil); //Se crea archivo FileInput para la lectura
            // Crear el objeto que tendra el libro de Excel
            XSSFWorkbook workbook = new XSSFWorkbook(file);
            /*
         * Obtenemos la primera pestaña a la que se quiera procesar indicando el indice.
         * Una vez obtenida la hoja excel con las filas que se quieren leer obtenemos el iterator
         * que nos permite recorrer cada una de las filas que contiene.
             */
            XSSFSheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rowIterator = sheet.iterator();
            Row row;
            // Recorremos todas las filas para mostrar el contenido de cada celda
            while (rowIterator.hasNext()) {
                row = rowIterator.next();
                // Obtenemos el iterator que permite recorres todas las celdas de una fila
                Iterator<Cell> cellIterator = row.cellIterator();
                Cell celda;
                while (cellIterator.hasNext()) {
                    celda = cellIterator.next();
                    // Dependiendo del formato de la celda el valor se debe mostrar como String, Fecha, boolean, entero...
                    switch (celda.getCellType()) {
                        case Cell.CELL_TYPE_NUMERIC:
                            if (DateUtil.isCellDateFormatted(celda)) {
                                // System.out.println(celda.getDateCellValue());
                            } else {
                                //System.out.println(celda.getNumericCellValue());
                            }
                            break;
                        case Cell.CELL_TYPE_STRING:
                            String item = "";
                            item = celda.getStringCellValue(); //Tomamos el valor de la celda
                            if (item.startsWith("<") && item.endsWith(">")) { //validamos que el contenido de la celda comience por < y termine en >
                                item = item.toLowerCase(); //Hago todo el item en minuscula
                                item = item.replace(">", "");
                                item = item.replace("<", "");
                                System.out.println("ITEM: "+item);
                                Merge(celda, item); //enviamos donde se le cambiará el item por el valor
                            }
                            break;
                        case Cell.CELL_TYPE_BOOLEAN:
                            System.out.println(celda.getBooleanCellValue());
                            break;
                    }
                }
            }
            // cerramos el libro excel
            file.close();
            //Se genera el nuevo archivo con los datos cambiados
            NewDocumento = "A01_" + "MergeFULL_" + document1 + "_SASPRUEBA_XLSX" + type1; //Creamos el nombre del documento
            NewDocumento = ruta1 + NewDocumento; //Agregamos el nombre del documento a la ruta donde se almacena
            FileOutputStream fileOut = new FileOutputStream(NewDocumento); //Doy la ruta y el nombre del archivo nuevo que se generará
            workbook.write(fileOut); //Escribo el nuevo archivo
            fileOut.close(); //Cierro el archivo

        } catch (Exception ex) {
            System.out.println("ERROR: " + ex);
        }
    }

    public static void Merge(Cell cell, String item) {
        if (item.equals("item1")) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue("Fabian Dario Montoya");
        } else if (item.equals("item3")) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue("Excel_GO");
        } else {
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue("Item_not_found");
        }
    }

    public static void main(String args[]) throws IOException, FileNotFoundException, InvalidFormatException {

        Documento = ruta1 + document1 + type1.toLowerCase();
        //Documento = ruta2+document2+type2;

        if (Documento.endsWith(".xlsx")) {
            XLSX(Documento);
            System.out.println("====??? GENERADO DOCUMENT XLSX ???======");
        } else if (Documento.endsWith(".xls")) {
            XLS(Documento);
            System.out.println("====??? GENERADO DOCUMENT XLS ???======");
        } else {
            System.out.println("Document not have the correct format!, please check it.");
        }

    }
    
answered by 17.11.2016 / 14:27
source
0

The same library allows you to create documents in Excel and modify, just search the web "generate excel with apache poi in java" there are too many examples, I do not understand what you want to do in Excel.

I think something like that would have to be adapted so that it does not go through all the excel ...

    //Recorrido por filas
    Iterator<Row> rowIterator = sheet.iterator();
    while (rowIterator.hasNext()) {
        Row row = rowIterator.next();
        rowIndex = row.getRowNum();

       int rowIndex2 = rowIndex +1;
       Iterator<Cell> cellIterator = row.cellIterator();
       //Recorrido por columnas
       while (cellIterator.hasNext()) {
           String valorCelda = cell.getStringCellValue().trim();
           if(valorcelda.equals("<item9>")){
                //Cambiamos valor de la celda
           }
       }
    }
    
answered by 04.11.2016 в 23:22