excel - Excel 数据中的变音符号
问题描述
我正在从 Excel 读取数据,如果单元格中的文本包含变音符号 (äöü),我的 Perl 脚本无法正确看到它们。char 被替换字符替换。
我需要做什么才能正确读取 Excel 中的特殊字符?
# get reference to Excel, Active Window, Active Sheet
my $excel = Win32::OLE->GetActiveObject('Excel.Application');
my $book = $excel -> ActiveWindow;
my $sheet = $book -> ActiveSheet();
my $text = $sheet->Cells(1, 2)->{Value};
解决方案
在将内容打印到 Windows 命令提示符窗口并使用 STDOUT 编码时,它适用于我(Windows 10、Strawberry Perl 5.30)cp437
:
use feature qw(say);
use strict;
use warnings;
use Win32::OLE;
use open ':std', ':encoding(cp437)';
# get reference to Excel, Active Window, Active Sheet
my $excel = Win32::OLE->GetActiveObject('Excel.Application');
my $book = $excel -> ActiveWindow;
my $sheet = $book -> ActiveSheet();
my $text = $sheet->Cells(1, 1)->{Value};
say $text;
输出:
äöü
编辑:
正如@ikegami 所指出的,您应该以编程方式确定控制台输出代码页(而不是cp437
像我那样对值进行硬编码),如下所示:
use Win32;
my $coe = "cp" . Win32::GetConsoleOutputCP();
binmode STDOUT, "encoding($coe)";
另请参阅这篇文章以获取更多信息。