Создать элемент на новом листе при создании книги - PullRequest
0 голосов
/ 15 октября 2019

На самом деле я пытаюсь вставить файлы Excel (функция уже выполнена и работает нормально) в лист на созданной книге.

Я создал небольшой цикл, который создает 5 листов, но я понятия не имею, как я могу вставить его благодаря функции внутри листов.

Вот основная функция, в которой я создаю и вставляю элемент вРабочая тетрадь.

Функция exportSyntheseProjetPvValide:

//Function to create the main Excel file
@GET
@Path("synthese-projet-PvValide/{annee:\\d+}/{mois:\\d+}/{statusProject:\\d+}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportSyntheseProjetPvValide(@PathParam("annee") final int annee, @PathParam("mois") final int mois,
        @PathParam("statusProject") final int status, @Context final SecurityContext context) throws Exception {

    // Get data base data
    final List<IndicateursGlobal> dataStaffing = indicateursResource.getIndicateurSynthese(annee, mois, status, context);

    WritableWorkbook copy = null;

    // Excel export
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {
        final Workbook workbook = Workbook.getWorkbook(new ClassPathResource("exportModel/syntheseGlobalePvValide.xls").getInputStream());
        copy = Workbook.createWorkbook(outStream, workbook, new WorkbookSettings());

        final WritableSheet sheetStaffing = copy.getSheet(0);

        //test to create 5 sheets
        for (int i = 0; i <= 5; i++) {
            copy.createSheet("sheet number " + i + " test", i);
            //Is it here that i can called a function to insert inside for my needs ? 
        }


        sheetStaffing.setName("syntheseGlobalePvValide");

        calculateExcelStaffingSynthesePvValide(dataStaffing, sheetStaffing);
        copy.write();


    } finally {
        if (copy != null) {
            copy.close();
        }
    }

    return Response.ok(new ByteArrayInputStream(outStream.toByteArray())).header(STR_TYPE_HEADER, "attachment; filename=syntheseGlobalePvValide.xls")
            .type(STR_TYPE_DOCUMENT).build();

}

Вот функция, которую мне нужно использовать для вставки в лист:

/**
 * @param id
 * @param context
 * @param uriInfo
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException 
 * @throws ClassNotFoundException
 * @throws IOException
 * @throws BiffException
 * @throws IndexOutOfBoundsException
 * @throws WriteException
 */
@GET
//Function that I must insert in sheet on inside the workbook
private ByteArrayOutputStream doExportBilan(final int id, final SecurityContext context, final UriInfo uriInfo) throws InstantiationException,
        IllegalAccessException, ClassNotFoundException, IOException, BiffException, IndexOutOfBoundsException, WriteException {
    final ProjectGroupamaDetailsVo projet = ProjectGroupamaResource.TO_BUSINESS_CONVERTER_DETAILS.apply(repositoryProjet.findOneExpected(id));


    final List<Delivery> listDeliv = repositoryDelivery.findByIdProjet(projet.getId());

    final List<SaisieAnomalieProjetDisplayVo> listAnos = Lists.transform(saisieAnomalieProjetRepository.findByIdProjet(projet.getId()),
            SaisieAnomalieProjetResource.TO_BUSINESS_DISPLAY_CONVERTER);

    final List<SaisieSyntheseVo> listSaisie = saisieProjetResource.getSyntheseSaisie(uriInfo, context, String.valueOf(projet.getId()));

    final List<SaisieDemandeChangement> listDem = saisieDemandeChangementResource.findAll(uriInfo, projet.getId()).getAaData();

    final Calendar cal = Calendar.getInstance();
    final int annee = cal.get(Calendar.YEAR);
    final int mois = cal.get(Calendar.MONTH) + 1;

    final IndicateursGlobal indic = indicateursResource.getIndicateurs(projet.getId(), annee, mois);

    WritableWorkbook copy = null;

    // Excel export
    final ByteArrayOutputStream outStream = new ByteArrayOutputStream();

    try {
        final WorkbookSettings ws = new WorkbookSettings();
        ws.setEncoding("Cp1252");

        final Workbook workbook = Workbook.getWorkbook(new ClassPathResource("exportModel/bilanProjet.xls").getInputStream(), ws);
        copy = Workbook.createWorkbook(outStream, workbook, new WorkbookSettings());

        final WritableSheet sheetStaffing = copy.getSheet(0);

        //Name project inside sheet Excel
        final String projetNom = projet.getName();
        sheetStaffing.setName("Projet_" + projetNom);

        calculateExcelBilanProjet(projet, listDeliv, listSaisie, listAnos, indic, listDem, sheetStaffing);

        copy.write();

    } finally {
        if (copy != null) {
            copy.close();
        }
    } 
    return outStream;
}

Я получаю доступ к этой функции благодаря этой функции:

//Acces to the second function thnaks to the PATH
@GET
@Path("bilan-projet/{id:\\d+}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response exportBilanProjet(@PathParam("id") final int id, @Context final SecurityContext context, @Context final UriInfo uriInfo)
        throws Exception {

    // final List<Project> listProject = projectRepository.findAll();
    final ProjectGroupamaDetailsVo projet = ProjectGroupamaResource.TO_BUSINESS_CONVERTER_DETAILS.apply(repositoryProjet.findOneExpected(id));
    final ByteArrayOutputStream outStream = doExportBilan(id, context, uriInfo);

    //Name project when the export is done
    final String projetNom = projet.getName();
    String nomDevis = projet.getNomDevis();
    String statut = "";


    if (projet.getStatutProjet() == 3 || projet.getStatutProjet() == 8 || projet.getStatutProjet() == 9) {
        statut = "PV réception définitive  V1";
    } else {
        statut = "PV fin garantie V1";
    }

    if (nomDevis == null || nomDevis.equals("")) {
        nomDevis = projetNom;
    }

    return Response.ok(new ByteArrayInputStream(outStream.toByteArray())).header(STR_TYPE_HEADER, "attachment; filename=" + nomDevis + "-EXI-" + statut + ".xls")
            .type(STR_TYPE_DOCUMENT).build();
}

Поэтому, когда я нажимаю кнопку, чтобы создать файл Excel, у меня должен быть основной файл Excel с некоторым листом внутри (вторая функция), в зависимости от того, сколько элементов было в таблице, когда я щелкал, чтобы загрузитьфайл (часть Javascript).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...