我目前正在使用 XSLT 开发 CSV 导出。在我的例子中,CSV 文件将与 Excel 一起使用 %99%,因此我必须考虑 Excel 的行为。
我的第一个问题是 csv 中的德语特殊字符。即使 CSV 编码是 UTF8,Excel 也无法正确打开 UTF8 的 CSV 文件。特殊字符变得奇怪的符号。我找到了解决这个问题的方法。我刚刚添加了 3 个额外字节(EF BB BF http://en.wikipedia.org/wiki/Byte_order_mark- 又名 BOM 标头) 内容字节的开头。因为 UTF8 BOM 是对 Excel 说“嘿伙计,它是 UTF8,正确打开它”的方式。问题解决了!
我的第二个问题是关于分隔符的。默认分隔符可以是逗号或分号,具体取决于区域。我认为在德国是分号,在英国是逗号。因此,为了防止这个问题,我必须添加以下行:
<xsl:text>sep=;</xsl:text>
or
<xsl:text>sep=,</xsl:text>
(此分隔符未作为硬编码实现)
但我找不到任何解决方案的问题是,如果您添加“sep=;”或“sep=”文件开头,而使用 UT8-BOM 生成 CSV 文件时,BOM 不再有助于正确显示特殊字符!我确信 BOM 字节始终位于字节数组的开头。此屏幕截图来自 Mac OS X 中的 MS Excel:
前 3 个符号属于 BOM 标头。
您是否曾经遇到过这样的问题或者您有什么建议吗?谢谢。
Edit:
我分享打印屏幕。
A。带有 BOM 和 <xsl:text>sep=;</xsl:text>
b.仅需BOM
Java代码:
// Write the bytes
ServletOutputStream out = resp.getOutputStream();
if(contentType.toString().equals("CSV")) {
// The additional bytes in below is prefix indicates that the content is in UTF-8.
out.write(239);
out.write(187);
out.write(191);
}
out.write(bytes); // Content bytes, in this case XSL
XSL 代码:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" version="1.0" encoding="UTF-8" indent="yes" />
<xsl:template match="/">
<xsl:text>sep=;</xsl:text>
<table>
...
</table>
</xsl:template>