apache poi中文自动调整列宽

问题描述 投票:0回答:1

Apache poi中文自动列宽调整不准确

有中文的时候

应该如何设置才能正确调整中文栏宽?

我这里有些专栏没有汉字,所以无法同时展开。

apache-poi
1个回答
0
投票

Apache POI 使用 SheetUtil 根据文本计算所需的单元格宽度。这使用了TextLayout。但到目前为止,具有

TextAttribute.WIDTH_REGULAR
的默认文本字形和其他字形(例如 CJKV(中文、日文、韩文和越南文)表意文字或杂项符号和象形文字或...)之间没有区别,它们需要更大的扩展宽度。

可以修补

org.apache.poi.ss.util.SheetUtil
以获得一种方法:

/**
 * Set text TextAttribute.WIDTH to Java2D AttributedString dependent on whether character is ideographic 
 * or miscellaneous symbols and pictographs
 * or ...
 */
private static void setTextAttributeWidth(String txt, AttributedString str) {
    float textAttributeWidth = 0.0f;
    int codePoints = 0;
    for (int offset = 0; offset < txt.length(); ) {
        int codePoint = txt.codePointAt(offset);
        if (Character.isIdeographic(codePoint)) { // if the specified character (Unicode code point) is a CJKV (Chinese, Japanese, Korean and Vietnamese) ideograph
            textAttributeWidth += (TextAttribute.WIDTH_REGULAR * 2.25);  
        } else if (codePoint >= 0x1F000 && codePoint <= 0x1FFFF) { // if in code point range 0x1F000 to 0x1FFFF; miscellaneous symbols and pictographs
            textAttributeWidth += (TextAttribute.WIDTH_REGULAR * 3.0);  
        } else if (false /*ToDo ... other things*/) {
            //textAttributeWidth += /*ToDo*/;  
        } else {
            textAttributeWidth += TextAttribute.WIDTH_REGULAR;
        }
        offset += Character.charCount(codePoint);
        codePoints++;
    }
    textAttributeWidth = textAttributeWidth / codePoints;
    str.addAttribute(TextAttribute.WIDTH, textAttributeWidth);
}

copyAttributes(font, str, 0, txt.length());
被调用时总是被调用:

...
AttributedString str = new AttributedString(txt);
setTextAttributeWidth(txt, str);
copyAttributes(font, str, 0, txt.length());
...

这将是具有

TextAttribute.WIDTH_REGULAR
的默认文本字形与其他需要更多扩展宽度的默认文本字形之间的区别。

我已经尝试过此操作,并在自动调整具有字符串内容的单元格大小时获得可靠的结果,例如:

...
String[] testStrings = new String[] {
    "default text",
    "用中文說「世界你好」",
    "lorem default text ipsum",
    "lorem 用中文說「世界你好」 ipsum",
    "😀😍🙂‍↔️",   
    "lorem 😀😍🙂‍↔️ ipsum"   
};
...
© www.soinside.com 2019 - 2024. All rights reserved.