在VC中导出文本,特别是含有中文字符的文本,常会碰到用excel打开为乱码,而用记事本打开则正常的状况,经研究,用下述方法可以解决该问题
关键方法:
1, 使用MultiByteToWideChar() API
2, 用CFile写入文件而非CStdioFile
3, 写入0xFF,0xFE至文件头部,以告知excel等外部编辑器打开的文本是unicode编码
4, CFile::Write()时注意写入的字节数
以导出.csv文件为例
//-- Tell execl that we are unicode
char tc[2];
tc[0] = (char)0xFF;
tc[1] = (char)0xFE;
ExportFile.Write(tc, 2);
//-- transform to unicode
LPWSTR p_wchar = NULL;
szLen = sz.GetLength();
p_wchar = new WCHAR[++szLen];
TransformedCount = MultiByteToWideChar(CP_ACP, 0, sz.GetBuffer(), szLen, p_wchar, szLen);
sz.ReleaseBuffer();
p_wchar[TransformedCount] = 0;
ExportFile.Write(p_wchar, wcslen(p_wchar)*sizeof(WCHAR));