我有一个Excel文件,其中有一些西班牙字符(波浪号等),我需要将其转换为CSV文件作为导入文件使用。然而,当我将另存为CSV时,它会破坏不是ASCII字符的“特殊”西班牙字符。它似乎也这样做的左右引号和长破折号,似乎是来自最初的用户在Mac中创建Excel文件。

由于CSV只是一个文本文件,我确信它可以处理UTF8编码,所以我猜这是Excel的限制,但我正在寻找一种方法,从Excel到CSV,并保持非ascii字符完整。


当前回答

将xls文件(Excel文件)保存为Unicode text=>文件将保存为文本格式(.txt) 将格式从.txt更改为.csv(将文件从xyz .txt重命名为xyz .csv

其他回答

对于那些有崇高的文本:保存编码utf-16 LE与BOM应该这样做;-)

另一个我觉得有用的例子是: “数字”允许在保存为CSV时进行编码设置。

您可以将excel保存为unicode文本,它是制表符分隔的。

对于那些寻找完全程序化(或者至少是服务器端)解决方案的人来说,我使用catdoc的xls2csv工具取得了巨大的成功。

安装catdoc:

apt-get install catdoc

进行转换:

xls2csv -d utf-8 file.xls > file-utf-8.csv 

这是非常快的。

请注意,包含-d utf-8标志非常重要,否则它将以默认的cp1252编码方式对输出进行编码,并且您将面临丢失信息的风险。

注意,xls2csv也只适用于.xls文件,它不适用于.xlsx文件。

I needed to automate this process on my Mac. I originally tried using catdoc/xls2csv as suggested by mpowered, but xls2csv had trouble detecting the original encoding of the document and not all documents were the same. What I ended up doing was setting the default webpage output encoding to be UTF-8 and then providing the files to Apple's Automator, applying the Convert Format of Excel Files action to convert to Web Page (HTML). Then using PHP, DOMDocument and XPath, I queried the documents and formatted them to CSV.

这是PHP脚本(process.php):

<?php
$pi = pathinfo($argv[1]);
$file = $pi['dirname'] . '/' . $pi['filename'] . '.csv';
$fp = fopen($file,'w+');
$doc = new DOMDocument;
$doc->loadHTMLFile($argv[1]);
$xpath = new DOMXPath($doc);
$table = [];
foreach($xpath->query('//tr') as $row){
    $_r = [];
    foreach($xpath->query('td',$row) as $col){
        $_r[] = trim($col->textContent);
    }
    fputcsv($fp,$_r);
}
fclose($fp);
?>

这是我用来将HTML文档转换为csv的shell命令:

find . -name '*.htm' | xargs -I{} php ./process.php {}

这是一种非常非常迂回的方法,但这是我发现的最可靠的方法。