So füllen Sie Daten in Spring Boot dynamisch in den Dokument von Word Dokument in Tripel einJava

Java-Forum
Anonymous
 So füllen Sie Daten in Spring Boot dynamisch in den Dokument von Word Dokument in Tripel ein

Post by Anonymous »

Ich bin in einem Java Spring Boot -Projekt. Derzeit erhielt ich die Aufgabe, dynamische Daten (von der Frontendanfrage DTO zu befragen) zu füllen, um die WordDocument -Vorlage zu sprudeln, und dass Daten vor diesem zum Download verfügbaren Tempat besiedelt werden sollten (das sollte im Wortformat sein und diese Vorlage mit Formaten existieren (Styles -Schriftarten Bild usw.). Die Platzhalter haben nicht mit den Daten apache poi und poi-tl ausprobiert, aber ich konnte es nicht auflösen. Ersetzen Sie den Platzhalter nicht durch Daten, da jeder Ort Inhaber Teil eines unterschiedlichen Laufs ist.

Code: Select all

/**
* Downloads the Memorandum of Understanding (MoU) template and sends it as a
* response.  Retrieves the template from the classpath, sets appropriate
* response headers, and streams the document content for download.
*
* @param response the HttpServletResponse used to send the file to the client
* @throws CollegeException if the template file is missing or an error occurs
*                          while streaming data
*/
@Override
public void downloadMouTemplate(HttpServletResponse response, MouTemplateRequestDTO mouTemplateDto) {
log.info("CollegeServiceImpl :: downloadTemplate()");

try {
ClassPathResource fileResource = new ClassPathResource("templates/myWordDoc.docx");

// Validate if the file exists before proceeding
if (!fileResource.exists() || fileResource.contentLength() == 0) {
log.error("MoU template file not found or empty");
throw new CollegeException("Template file not found");
}

try (InputStream fileStream = fileResource.getInputStream();
XWPFDocument document = new XWPFDocument(fileStream);
OutputStream outputStream = response.getOutputStream()) {

HashMap collegeMap = new HashMap();
collegeMap.put("collegeName", mouTemplateDto.getCollegeName());
collegeMap.put("collegeAddress", mouTemplateDto.getCollegeAddress());
replacePlaceholders(document, collegeMap);

response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
response.setHeader("Content-Disposition", "attachment; filename=\"myWordDocuement.docx\"");
response.setStatus(HttpServletResponse.SC_OK);

document.write(outputStream);
response.flushBuffer();

} catch (IOException e) {
log.error("Error while reading the file", e.getMessage());
throw new CollegeException("Error while reading the MoU template file");
}

} catch (CollegeException e) {
log.error("Template Not found exception: {}", e.getMessage());
throw e;
} catch (Exception e) {
log.error("Unexpected error while downloading the MoU template", e.getMessage());
throw new CollegeException("Unexpected error while downloading the MoU template.");
}
}

private static void replacePlaceholders(XWPFDocument document, Map data) {
// Replace placeholders in document paragraphs
for (XWPFParagraph paragraph : document.getParagraphs()) {
replacePlaceholdersInParagraph(paragraph, data);
}

// Replace placeholders inside tables
for (XWPFTable table : document.getTables()) {
for (XWPFTableRow row : table.getRows()) {
for (XWPFTableCell cell : row.getTableCells()) {
for (XWPFParagraph paragraph : cell.getParagraphs()) {
replacePlaceholdersInParagraph(paragraph, data); // Call the correct method
}
}
}
}
}

private static void replacePlaceholdersInParagraph(XWPFParagraph paragraph, Map data){ List runs = paragraph.getRuns();
if (runs != null && !runs.isEmpty()) {
StringBuilder fullText = new StringBuilder();

for (XWPFRun run : runs) {
String runText = run.getText(0);
if (runText != null) {
fullText.append(runText);
}
}

// Replace placeholders
String updatedText = fullText.toString();
for (Map.Entry entry : data.entrySet()) {
updatedText = updatedText.replace("${" + entry.getKey() + "}", entry.getValue());
}

// Remove existing runs to maintain formatting
for (int i = runs.size() - 1; i >= 0; i--) {
paragraph.removeRun(i);
}

// Create a new run with replaced text
XWPFRun newRun = paragraph.createRun();
newRun.setText(updatedText);
}
}
Inside MyWordDoc -Absatz -
$ {Collegname} Eine mit VTU verbundene Bildungseinrichtung und befindet sich bei $ {CollegadDress} (nachstehend als "College".

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post