Hello,
I’m facing an issue that decimal number is not interpreted in the else condition of the if…then…else merged field. Below is code snippet to reproduce this problem. Note: this issue happens on Aspose Word 20.3 (using in production) and 20.11
public class HandleMailMergeNumbers {
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(HandleMailMergeNumbers.class) + "MailMerge/";
// Open an existing document.
Document doc = new Document(dataDir + "MailMergeNumbers.docx");
//Remove merge field with empty value and if the row are empty=> remove paragraph
doc.getMailMerge().setCleanupOptions(MailMergeCleanupOptions.REMOVE_UNUSED_FIELDS
| MailMergeCleanupOptions.REMOVE_EMPTY_PARAGRAPHS
| MailMergeCleanupOptions.REMOVE_UNUSED_REGIONS
| MailMergeCleanupOptions.REMOVE_CONTAINING_FIELDS);
doc.getMailMerge().setFieldMergingCallback(new CustomedFieldMergingCallback());
doc.getMailMerge().setUnconditionalMergeFieldsAndRegions(true);
// Fill the fields in the document with user data.
doc.getMailMerge().execute(
new String[]{"testNumber", "quantite", "sousFamilleProduit", "otherAttr"},
new Object[]{"123456.9", 0.0, "abc", 11111.0});
dataDir = dataDir + "MergeNumbers_out.doc";
doc.save(dataDir);
System.out.println("\nSimple Mail merge performed with array data successfully.\nFile saved at " + dataDir);
}
}
public class CustomedFieldMergingCallback implements IFieldMergingCallback {
@Override
public void fieldMerging(FieldMergingArgs fma) throws Exception {
if (fma.getField().getFormat().getNumericFormat() != null && !fma.getField().getFormat().getNumericFormat().isEmpty()) {
if (fma.getFieldValue() != null && !StringUtils.isBlank(fma.getFieldValue().toString())) {
DocumentBuilder builder = new DocumentBuilder(fma.getDocument());
String languageTag = LanguageCode.FRENCH.getCode();
String formatString = fma.getField().getFormat().getNumericFormat();
String formatPattern = formatString;
if (formatString.contains(":")) {
String[] formatParts = formatString.split(":");
languageTag = formatParts[0];
formatPattern = formatParts[1];
}
DecimalFormatSymbols formatSymbol = new DecimalFormatSymbols(Locale.forLanguageTag(languageTag));
if (Locale.forLanguageTag(languageTag).getLanguage().isEmpty()) {
formatSymbol = new DecimalFormatSymbols(Locale.forLanguageTag(LanguageCode.FRENCH.getCode()));
}
// This is to handle for Swiss French and undefined case
if ("fr_ch".equalsIgnoreCase(languageTag)) {
formatSymbol.setGroupingSeparator('\'');
formatSymbol.setDecimalSeparator('.');
}
DecimalFormat formatter = new DecimalFormat(formatPattern, formatSymbol);
Double value = Double.parseDouble(fma.getFieldValue().toString());
builder.moveToMergeField(fma.getFieldName());
builder.write(formatter.format(value));
}
}
}
...
}
sample output:
image.png (8.6 KB)
Note:
image.png (27.4 KB)
Test code and sample output:
testCode.zip (22.8 KB)
Thanks