This is an automated email from the ASF dual-hosted git repository.
pjfanning pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/poi.git
The following commit(s) were added to refs/heads/trunk by this push:
new 40ed8ac27e XSSF/SXSSF: optionally escape literal _xHHHH_ sequences on
write (#1415)
40ed8ac27e is described below
commit 40ed8ac27e9ed11e74bbe3df9128e6d73389ef47
Author: PJ Fanning <[email protected]>
AuthorDate: Fri Oct 16 20:26:27 2026 +0100
XSSF/SXSSF: optionally escape literal _xHHHH_ sequences on write (#1415)
* XSSF/SXSSF: optionally escape literal _xHHHH_ sequences on write
Adds public XSSFRichTextString.utfEncode(String) and makes utfDecode
public, so callers can escape text themselves.
Adds setEscapeLiteralUnicodeSequences(boolean) to XSSFWorkbook and
SXSSFWorkbook, off by default. When enabled, plain string cell values
and cached formula string results are stored with the leading
underscore of _xHHHH_ sequences escaped as _x005F_, as Excel does, so
they are read back unchanged.
Fixes #1410
Co-Authored-By: Claude Opus 5.5 <[email protected]>
* utfEncode: also escape characters that XML 1.0 cannot carry
With escaping enabled, the _x0001_ trick for writing control characters
is itself escaped, and the raw characters are replaced with '?' by
XMLBeans and SXSSF. Encode them as _xHHHH_, as ST_Xstring specifies and
Excel does, so utfEncode is a full inverse of utfDecode.
This is done in one pass, as an escaped character can close a preceding
_xHHHH sequence, which then needs its underscore escaped too.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---------
Co-authored-by: Claude Opus 5.5 <[email protected]>
---
.../org/apache/poi/xssf/streaming/SXSSFCell.java | 5 ++
.../apache/poi/xssf/streaming/SXSSFWorkbook.java | 29 ++++++++
.../apache/poi/xssf/streaming/SheetDataWriter.java | 17 +++--
.../org/apache/poi/xssf/usermodel/XSSFCell.java | 17 ++++-
.../poi/xssf/usermodel/XSSFRichTextString.java | 81 +++++++++++++++++++++-
.../apache/poi/xssf/usermodel/XSSFWorkbook.java | 42 +++++++++++
.../apache/poi/xssf/streaming/TestSXSSFCell.java | 43 ++++++++++++
.../apache/poi/xssf/usermodel/TestXSSFCell.java | 63 +++++++++++++++++
.../poi/xssf/usermodel/TestXSSFRichTextString.java | 31 +++++++++
9 files changed, 320 insertions(+), 8 deletions(-)
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFCell.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFCell.java
index 737e532051..d87b6b8d0b 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFCell.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFCell.java
@@ -991,6 +991,11 @@ public class SXSSFCell extends CellBase {
{
CellType getType();
}
+
+ boolean isRichTextValue() {
+ return _value instanceof RichTextValue;
+ }
+
static class NumericValue implements Value {
double _value;
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java
index ac03b2d1e4..5efc4e0735 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SXSSFWorkbook.java
@@ -377,6 +377,35 @@ public class SXSSFWorkbook implements Workbook {
return shouldCalculateSheetDimensions;
}
+ /**
+ * Whether literal <code>_xHHHH_</code> sequences in string cell values
are escaped when written.
+ * This sets the option on the underlying {@link XSSFWorkbook}.
+ * <p>
+ * Values set with {@link SXSSFCell#setCellValue(String)} and cached
formula string results are
+ * escaped. With a shared strings table, {@link XSSFRichTextString} values
are written as is, see
+ * {@link XSSFWorkbook#setEscapeLiteralUnicodeSequences(boolean)}. Inline
strings hold only the
+ * text of an {@link XSSFRichTextString}, so they are escaped and read
back as its
+ * {@link XSSFRichTextString#getString()}.
+ *
+ * @param value true to escape literal <code>_xHHHH_</code> sequences
+ * @see XSSFWorkbook#setEscapeLiteralUnicodeSequences(boolean)
+ * @since 6.0.0
+ */
+ public void setEscapeLiteralUnicodeSequences(boolean value) {
+ _wb.setEscapeLiteralUnicodeSequences(value);
+ }
+
+ /**
+ * Whether literal <code>_xHHHH_</code> sequences in string cell values
are escaped when written.
+ *
+ * @return true if literal <code>_xHHHH_</code> sequences are escaped
+ * @see #setEscapeLiteralUnicodeSequences(boolean)
+ * @since 6.0.0
+ */
+ public boolean isEscapeLiteralUnicodeSequences() {
+ return _wb.isEscapeLiteralUnicodeSequences();
+ }
+
@Internal
protected SharedStringsTable getSharedStringSource() {
return _sharedStringSource;
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SheetDataWriter.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SheetDataWriter.java
index 77ed527f54..ae5d000d56 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SheetDataWriter.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/streaming/SheetDataWriter.java
@@ -42,6 +42,7 @@ import org.apache.poi.ss.util.CellReference;
import org.apache.poi.util.CodepointsUtil;
import org.apache.poi.util.TempFile;
import org.apache.poi.xssf.model.SharedStringsTable;
+import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.STCellType;
/**
@@ -255,6 +256,8 @@ public class SheetDataWriter implements Closeable {
// APIs
writeAttribute("s", Integer.toString(cellStyle.getIndex() &
0xffff));
}
+ boolean encode = cell.getSheet().getWorkbook() instanceof
SXSSFWorkbook wb
+ && wb.isEscapeLiteralUnicodeSequences();
CellType cellType = cell.getCellType();
switch (cellType) {
case BLANK: {
@@ -292,7 +295,7 @@ public class SheetDataWriter implements Closeable {
String value = cell.getStringCellValue();
if(value != null && !value.isEmpty()) {
_out.write("<v>");
- outputEscapedString(value);
+ outputEscapedString(encode ?
XSSFRichTextString.utfEncode(value) : value);
_out.write("</v>");
}
break;
@@ -314,7 +317,12 @@ public class SheetDataWriter implements Closeable {
}
case STRING: {
if (_sharedStringSource != null) {
- RichTextString rt = cell.getRichStringCellValue();
+ // XSSFRichTextString values already hold the stored form
of the text
+ boolean encodeString = encode
+ && !(cell instanceof SXSSFCell sxCell &&
sxCell.isRichTextValue());
+ RichTextString rt = encodeString
+ ? new
XSSFRichTextString(XSSFRichTextString.utfEncode(cell.getStringCellValue()))
+ : cell.getRichStringCellValue();
int sRef = _sharedStringSource.addSharedStringItem(rt);
writeAttribute("t", STCellType.S.toString());
@@ -324,11 +332,12 @@ public class SheetDataWriter implements Closeable {
} else {
writeAttribute("t", "inlineStr");
_out.write("><is><t");
- if (hasLeadingTrailingSpaces(cell.getStringCellValue())) {
+ String value = cell.getStringCellValue();
+ if (hasLeadingTrailingSpaces(value)) {
writeAttribute("xml:space", "preserve");
}
_out.write(">");
- outputEscapedString(cell.getStringCellValue());
+ outputEscapedString(encode ?
XSSFRichTextString.utfEncode(value) : value);
_out.write("</t></is>");
}
break;
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFCell.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFCell.java
index ea03fb79f7..3f6d2b026c 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFCell.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFCell.java
@@ -350,7 +350,7 @@ public final class XSSFCell extends CellBase {
@Override
protected void setCellValueImpl(String value) {
- setCellValueImpl(new XSSFRichTextString(value));
+ setCellValueImpl(new XSSFRichTextString(encodeIfEnabled(value)));
}
@Override
@@ -358,7 +358,7 @@ public final class XSSFCell extends CellBase {
removeInlineString();
CellType cellType = getCellType();
if (cellType == CellType.FORMULA) {
- _cell.setV(str.getString());
+ _cell.setV(encodeIfEnabled(str.getString()));
_cell.setT(STCellType.STR);
} else if (str instanceof XSSFRichTextString) {
_cell.setT(STCellType.S);
@@ -368,13 +368,24 @@ public final class XSSFCell extends CellBase {
_cell.setV(Integer.toString(sRef));
} else {
_cell.setT(STCellType.S);
- XSSFRichTextString rt = new XSSFRichTextString(str.getString());
+ XSSFRichTextString rt = new
XSSFRichTextString(encodeIfEnabled(str.getString()));
rt.setStylesTableReference(_stylesSource);
int sRef = _sharedStringSource.addSharedStringItem(rt);
_cell.setV(Integer.toString(sRef));
}
}
+ /**
+ * Escapes literal <code>_xHHHH_</code> sequences in text that is about to
be stored,
+ * if the workbook asks for it.
+ *
+ * @see XSSFWorkbook#setEscapeLiteralUnicodeSequences(boolean)
+ */
+ private String encodeIfEnabled(String value) {
+ return getSheet().getWorkbook().isEscapeLiteralUnicodeSequences()
+ ? XSSFRichTextString.utfEncode(value) : value;
+ }
+
/**
* Return a formula for the cell, for example, {@code SUM(C4:E4)}
*
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
index 8167fa8ea4..1faec26bcb 100644
---
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
+++
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
@@ -32,6 +32,7 @@ import
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
import javax.xml.namespace.QName;
import java.util.Iterator;
+import java.util.Locale;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
@@ -536,8 +537,10 @@ public class XSSFRichTextString implements RichTextString {
*
* @param value the string to decode
* @return the decoded string or null if the input string is null
+ * @see #utfEncode(String)
+ * @since 6.0.0
*/
- static String utfDecode(String value) {
+ public static String utfDecode(String value) {
if(value == null || !value.contains("_x")) {
return value;
}
@@ -568,6 +571,82 @@ public class XSSFRichTextString implements RichTextString {
return buf.toString();
}
+ /**
+ * Encodes a string so that it survives a round trip through {@link
#utfDecode(String)},
+ * using the <code>_xHHHH_</code> escapes defined for
<code>ST_Xstring</code> in the OOXML spec.
+ * <ul>
+ * <li>The leading underscore of literal text that would otherwise be read
as a
+ * <code>_xHHHH_</code> escape is written as <code>_x005F_</code>, as
Excel does,
+ * e.g. <code>_x0041_</code> becomes <code>_x005F_x0041_</code>.</li>
+ * <li>Characters that cannot be represented in XML 1.0 (control
characters other than
+ * tab, line feed and carriage return, and U+FFFE/U+FFFF) are escaped,
+ * e.g. U+0001 becomes <code>_x0001_</code>.</li>
+ * </ul>
+ *
+ * @param value the string to encode
+ * @return the encoded string or null if the input string is null
+ * @see #utfDecode(String)
+ * @see XSSFWorkbook#setEscapeLiteralUnicodeSequences(boolean)
+ * @since 6.0.0
+ */
+ public static String utfEncode(String value) {
+ if (value == null) {
+ return null;
+ }
+ StringBuilder buf = null;
+ final int len = value.length();
+ for (int i = 0; i < len; i++) {
+ final char c = value.charAt(i);
+ final boolean escape = isInvalidXmlChar(c) || (c == '_' &&
startsEscapeSequence(value, i));
+ if (escape) {
+ if (buf == null) {
+ buf = new StringBuilder(len + 16);
+ buf.append(value, 0, i);
+ }
+ appendEscape(buf, c);
+ } else if (buf != null) {
+ buf.append(c);
+ }
+ }
+ // the encodings are rare, so we should almost always return the input
+ return buf == null ? value : buf.toString();
+ }
+
+ /**
+ * Whether the underscore at {@code index} would start a
<code>_xHHHH_</code> escape
+ * once the string is encoded. An invalid XML character after the hex
digits counts as
+ * the closing underscore, as its own escape starts with one.
+ */
+ private static boolean startsEscapeSequence(String value, int index) {
+ if (index + 6 >= value.length() || value.charAt(index + 1) != 'x') {
+ return false;
+ }
+ for (int i = index + 2; i < index + 6; i++) {
+ if (!isHexDigit(value.charAt(i))) {
+ return false;
+ }
+ }
+ final char next = value.charAt(index + 6);
+ return next == '_' || isInvalidXmlChar(next);
+ }
+
+ private static boolean isHexDigit(char c) {
+ return (c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a'
&& c <= 'f');
+ }
+
+ private static boolean isInvalidXmlChar(char c) {
+ return (c < ' ' && c != '\t' && c != '\n' && c != '\r') || c ==
'\uFFFE' || c == '\uFFFF';
+ }
+
+ private static void appendEscape(StringBuilder buf, char c) {
+ buf.append("_x");
+ final String hex = Integer.toHexString(c).toUpperCase(Locale.ROOT);
+ for (int i = hex.length(); i < 4; i++) {
+ buf.append('0');
+ }
+ buf.append(hex).append('_');
+ }
+
void applyFont(TreeMap<Integer, CTRPrElt> formats, int startIndex, int
endIndex, CTRPrElt fmt) {
// delete format runs that fit between startIndex and endIndex
// runs intersecting startIndex and endIndex remain
diff --git
a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
index b1f98b2579..d2ed147da3 100644
--- a/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
+++ b/poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFWorkbook.java
@@ -193,6 +193,11 @@ public class XSSFWorkbook extends POIXMLDocument
implements Workbook, Date1904Su
*/
private boolean cellFormulaValidation = true;
+ /**
+ * Whether literal <code>_xHHHH_</code> sequences in string cell values
are escaped when stored.
+ */
+ private boolean escapeLiteralUnicodeSequences;
+
/**
* array of pictures for this workbook
*/
@@ -2615,6 +2620,43 @@ public class XSSFWorkbook extends POIXMLDocument
implements Workbook, Date1904Su
return this.cellFormulaValidation;
}
+ /**
+ * Whether literal <code>_xHHHH_</code> sequences in string cell values
are escaped when stored.
+ * <p>
+ * OOXML uses <code>_xHHHH_</code> to escape characters, and POI and Excel
decode such sequences
+ * when reading string values. Without escaping, a value such as
<code>_x0041_ col</code> is read
+ * back as <code>A col</code>. When this is enabled, the leading
underscore of such sequences is
+ * stored as <code>_x005F_</code> (see {@link
XSSFRichTextString#utfEncode(String)}), so the value
+ * is read back unchanged. Characters that cannot be represented in XML
1.0, such as U+0001,
+ * are stored as <code>_xHHHH_</code> escapes too, rather than being
replaced with <code>?</code>.
+ * <p>
+ * This applies to string values set with {@link
XSSFCell#setCellValue(String)}, to cached
+ * formula string results, and to {@link
org.apache.poi.ss.usermodel.RichTextString}s that are
+ * not {@link XSSFRichTextString}s. An {@link XSSFRichTextString} already
holds the stored form of its text (its
+ * {@link XSSFRichTextString#getString()} decodes <code>_xHHHH_</code>
sequences), so it is stored
+ * as is; use {@link XSSFRichTextString#utfEncode(String)} on the text you
put into it.
+ * <p>
+ * Defaults to {@code false}, which stores strings as given. This allows
deliberate escapes,
+ * e.g. <code>_x000D_</code>, to be written.
+ *
+ * @param value true to escape literal <code>_xHHHH_</code> sequences
+ * @since 6.0.0
+ */
+ public void setEscapeLiteralUnicodeSequences(boolean value) {
+ this.escapeLiteralUnicodeSequences = value;
+ }
+
+ /**
+ * Whether literal <code>_xHHHH_</code> sequences in string cell values
are escaped when stored.
+ *
+ * @return true if literal <code>_xHHHH_</code> sequences are escaped
+ * @see #setEscapeLiteralUnicodeSequences(boolean)
+ * @since 6.0.0
+ */
+ public boolean isEscapeLiteralUnicodeSequences() {
+ return this.escapeLiteralUnicodeSequences;
+ }
+
@Override
public XSSFEvaluationWorkbook createEvaluationWorkbook() {
return XSSFEvaluationWorkbook.create(this);
diff --git
a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFCell.java
b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFCell.java
index 894bc5c994..505ad955c4 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFCell.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/streaming/TestSXSSFCell.java
@@ -24,6 +24,7 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.spy;
import java.io.IOException;
@@ -41,11 +42,14 @@ import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.SXSSFITestDataProvider;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
+import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.xmlbeans.XmlCursor;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTRst;
/**
@@ -169,4 +173,43 @@ class TestSXSSFCell extends BaseTestXCell {
@Disabled
protected void setCellType_FORMULA_onAnArrayFormulaCell_doesNothing() {
}
+
+ @ParameterizedTest
+ @ValueSource(booleans = {true, false})
+ void testEscapeLiteralUnicodeSequences(boolean useSharedStringsTable)
throws IOException {
+ try (SXSSFWorkbook wb = new SXSSFWorkbook(null, 100, false,
useSharedStringsTable)) {
+ assertFalse(wb.isEscapeLiteralUnicodeSequences());
+ wb.setEscapeLiteralUnicodeSequences(true);
+ assertTrue(wb.isEscapeLiteralUnicodeSequences());
+ assertTrue(wb.getXSSFWorkbook().isEscapeLiteralUnicodeSequences());
+
+ SXSSFRow row = wb.createSheet().createRow(0);
+ row.createCell(0).setCellValue("_x0041_ col");
+ row.createCell(1).setCellValue("plain\u0001");
+ SXSSFCell formulaCell = row.createCell(2);
+ formulaCell.setCellFormula("\"_x0043_\"");
+ formulaCell.setCellValue("_x0043_");
+ row.createCell(3).setCellValue(new
XSSFRichTextString(XSSFRichTextString.utfEncode("_x0044_")));
+
+ try (XSSFWorkbook wb2 =
SXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
+ XSSFRow row2 = wb2.getSheetAt(0).getRow(0);
+ assertEquals("_x0041_ col",
row2.getCell(0).getStringCellValue());
+ assertEquals("plain\u0001",
row2.getCell(1).getStringCellValue());
+ assertEquals("_x0043_", row2.getCell(2).getStringCellValue());
+ assertEquals("_x0044_", row2.getCell(3).getStringCellValue());
+ }
+ wb.dispose();
+ }
+ }
+
+ @Test
+ void testNoEscapeLiteralUnicodeSequencesByDefault() throws IOException {
+ try (SXSSFWorkbook wb = new SXSSFWorkbook()) {
+ wb.createSheet().createRow(0).createCell(0).setCellValue("_x0041_
col");
+ try (XSSFWorkbook wb2 =
SXSSFITestDataProvider.instance.writeOutAndReadBack(wb)) {
+ assertEquals("A col",
wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
+ }
+ wb.dispose();
+ }
+ }
}
diff --git
a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java
b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java
index bd1aa990c4..dc2f5eb6c8 100644
--- a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java
+++ b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFCell.java
@@ -32,6 +32,7 @@ import java.util.List;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.HSSFITestDataProvider;
+import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.SpreadsheetVersion;
import org.apache.poi.ss.formula.FormulaParseException;
import org.apache.poi.ss.tests.usermodel.BaseTestXCell;
@@ -902,4 +903,66 @@ public final class TestXSSFCell extends BaseTestXCell {
cell.getCTCell().setIs(rst);
assertEquals(text, cell.getStringCellValue());
}
+
+ @Test
+ void testEscapeLiteralUnicodeSequences() throws IOException {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ assertFalse(wb.isEscapeLiteralUnicodeSequences());
+ XSSFSheet sheet = wb.createSheet();
+ XSSFRow row = sheet.createRow(0);
+ row.createCell(0).setCellValue("_x0041_ col");
+ row.createCell(1).setCellValue("_x000D_");
+
+ wb.setEscapeLiteralUnicodeSequences(true);
+ assertTrue(wb.isEscapeLiteralUnicodeSequences());
+ row.createCell(2).setCellValue("_x0041_ col");
+ row.createCell(3).setCellValue(new HSSFRichTextString("_x0042_"));
+ XSSFCell formulaCell = row.createCell(4);
+ formulaCell.setCellFormula("\"_x0043_\"");
+ formulaCell.setCellValue("_x0043_");
+ XSSFCell numericCell = row.createCell(5);
+ numericCell.setCellValue(1);
+ numericCell.setCellFormula("\"_x0044_\"");
+ numericCell.setCellValue("_x0044_");
+ // an XSSFRichTextString holds the stored form of its text, so it
is not escaped
+ row.createCell(6).setCellValue(new XSSFRichTextString("_x0045_"));
+ row.createCell(7).setCellValue(new
XSSFRichTextString(XSSFRichTextString.utfEncode("_x0046_")));
+ row.createCell(8).setCellValue("a\u0001b");
+
+ // in-memory values are the literal text
+ assertEquals("_x0041_ col", row.getCell(2).getStringCellValue());
+ assertEquals("_x0043_", formulaCell.getStringCellValue());
+
+ try (XSSFWorkbook wb2 =
XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ XSSFRow row2 = wb2.getSheetAt(0).getRow(0);
+ // written before the option was enabled
+ assertEquals("A col", row2.getCell(0).getStringCellValue());
+ assertEquals("\r", row2.getCell(1).getStringCellValue());
+
+ assertEquals("_x0041_ col",
row2.getCell(2).getStringCellValue());
+ assertEquals("_x0042_", row2.getCell(3).getStringCellValue());
+ assertEquals("_x0043_", row2.getCell(4).getStringCellValue());
+ assertEquals("_x0044_", row2.getCell(5).getStringCellValue());
+ assertEquals("E", row2.getCell(6).getStringCellValue());
+ assertEquals("_x0046_", row2.getCell(7).getStringCellValue());
+ assertEquals("a\u0001b", row2.getCell(8).getStringCellValue());
+ }
+ }
+ }
+
+ @Test
+ void testEscapeLiteralUnicodeSequencesSetCellType() throws IOException {
+ try (XSSFWorkbook wb = new XSSFWorkbook()) {
+ wb.setEscapeLiteralUnicodeSequences(true);
+ XSSFCell cell = wb.createSheet().createRow(0).createCell(0);
+ cell.setCellFormula("\"_x0041_\"");
+ cell.setCellValue("_x0041_");
+ cell.setCellType(CellType.STRING);
+ assertEquals("_x0041_", cell.getStringCellValue());
+
+ try (XSSFWorkbook wb2 =
XSSFTestDataSamples.writeOutAndReadBack(wb)) {
+ assertEquals("_x0041_",
wb2.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());
+ }
+ }
+ }
}
diff --git
a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java
b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java
index 1100e68a12..7f5118f118 100644
---
a/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java
+++
b/poi-ooxml/src/test/java/org/apache/poi/xssf/usermodel/TestXSSFRichTextString.java
@@ -244,6 +244,37 @@ public final class TestXSSFRichTextString {
assertEquals("abc\r2ef\r", rt2.getString());
}
+ @Test
+ void testUtfEncode() {
+ assertNull(XSSFRichTextString.utfEncode(null));
+ assertEquals("", XSSFRichTextString.utfEncode(""));
+ assertEquals("abc_x", XSSFRichTextString.utfEncode("abc_x"));
+ assertEquals("_x00G1_", XSSFRichTextString.utfEncode("_x00G1_"));
+ assertEquals("\t\n\r", XSSFRichTextString.utfEncode("\t\n\r"));
+ assertEquals("a_x0001_b_x001F__xFFFF_",
XSSFRichTextString.utfEncode("a\u0001b\u001F\uFFFF"));
+ // the control character's escape would close the _xABCD sequence
before it
+ assertEquals("_x005F_xABCD_x0001_",
XSSFRichTextString.utfEncode("_xABCD\u0001"));
+ assertEquals("_xAB_x0001_",
XSSFRichTextString.utfEncode("_xAB\u0001"));
+ assertEquals("_x\uFF10\uFF10\uFF10\uFF10_",
XSSFRichTextString.utfEncode("_x\uFF10\uFF10\uFF10\uFF10_"));
+ assertEquals("_x005F_x0041_ col",
XSSFRichTextString.utfEncode("_x0041_ col"));
+ assertEquals("a_x005F_x000d_b",
XSSFRichTextString.utfEncode("a_x000d_b"));
+ assertEquals("_x005F_x005F_x005F_x0041_",
XSSFRichTextString.utfEncode("_x005F_x0041_"));
+ // overlapping sequences: the second one would be decoded once the
first is escaped
+ assertEquals("_x005F_x0041_x005F_x0042_",
XSSFRichTextString.utfEncode("_x0041_x0042_"));
+ }
+
+ @Test
+ void testUtfEncodeRoundTrip() {
+ String[] values = {
+ "plain", "_x0041_", "_x0041_ col", "_x0041__x0042_",
"_x0041_x0042_",
+ "_x005F_", "_x005F_x0041_", "__x0041_", "_x00_x0041_",
"_x_x0041_", "_x000D_\r",
+ "a\u0001b", "\u0000", "_xABCD\u0001", "_x0041\u001F_",
"\uFFFE\uFFFF", "_x0041_\u0002"
+ };
+ for (String value : values) {
+ assertEquals(value,
XSSFRichTextString.utfDecode(XSSFRichTextString.utfEncode(value)), value);
+ }
+ }
+
@Test
void testApplyFont_lowlevel(){
CTRst st = CTRst.Factory.newInstance();
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]