我正在编写一个函数,旨在将列表控件的内容写入 Excel 文件。但是我发现输出的格式不是我想要的。我的代码是
{
CString buff0, buff1, buff2;
CString fileName = _T("d:\\test.xls");//
CFile file(fileName, CFile::modeCreate | CFile::modeReadWrite |
CFile::shareExclusive);
file.Write("A\tB\tC\n", 56);
int i = 0;
int j = 0;
j = m_list.GetItemCount();
if (j > 0)
{
for (i = 0; i<j; i++)
{
buff0 = _T("0"); % only for test, should be m_list.GetItemText()
buff1 = _T("1"); % for test
buff2 = _T("2"); % for test
CString msg;
msg.Format(_T("%s\t%s\t%s\n"), buff0, buff1, buff2);% output each line to Excel
file.Write(msg, msg.GetLength());
}
}
}
我发现 msg.Format(_T("%s\t%s\t%s\n"), buff0, buff1, buff2); 没有按照我的意愿执行。输出的 Excel 文件就像
但根据 msg.Format(_T("%s\t%s\t%s\n"), buff0, buff1, buff2); 每行应该是 3 个元素 (0,1,2);
然而 file.Write("A\tB\tC\n", 56); 按意愿执行。
任何人都知道是什么问题。非常感谢!
您正在以 UTF-16 格式写入文件。msg.GetLength()
返回wchar_t
字符串中的数字,它是缓冲区中总长度的一半(在本例中)。如果你这样写L"12345\n"
,它可能会显示为" 1 2 3"
ANSI,其余的字符串都丢失了。
在file.Write("A\tB\tC\n", 56)
您分配一个比缓冲区大的任意数字 56 时,它恰好可以工作。
您应该以 ANSI 格式写入文件,或将 UTF-16 更改为 UTF-8 以保留 Unicode。例子:
CStringA u8 = CW2A(_T("A\tB\tC\n"), CP_UTF8);
file.Write(u8, u8.GetLength());
for(...)
{
buff0 = _T("0");
buff1 = _T("1");
buff2 = _T("2");
CString msg;
msg.Format(_T("%s\t%s\t%s\n"),
(LPCTSTR)buff0, (LPCTSTR)buff1, (LPCTSTR)buff2);
u8 = CW2A(msg, CP_UTF8);
file.Write(u8, u8.GetLength());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句