关于将列表控件写入Excel文件的MFC问题
我正在编写一个函数,旨在将列表控件的内容写入Excel文件。但是我发现输出的格式不是我所希望的。我的代码是关于将列表控件写入Excel文件的MFC问题,excel,mfc,listcontrol,Excel,Mfc,Listcontrol,我正在编写一个函数,旨在将列表控件的内容写入Excel文件。但是我发现输出的格式不是我所希望的。我的代码是 { CString buff0, buff1, buff2; CString fileName = _T("d:\\test.xls");// CFile file(fileName, CFile::modeCreate | CFile::modeReadWrite | CFile::shareExclusive);
{
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());
}
}
}
{
CString buff0、buff1、buff2;
CString文件名=_T(“d:\\test.xls”)//
CFile文件(文件名,CFile::modeCreate | CFile::modeReadWrite |
CFile::shareExclusive);
Write(“A\tB\tC\n”,56);
int i=0;
int j=0;
j=m_list.GetItemCount();
如果(j>0)
{
对于(i=0;i您正在UTF-16中写入文件。msg.GetLength()
返回字符串中wchar\u t
的数量,这是缓冲区中总长度的一半(在本例中)。如果您以这种方式写入L“12345\n”
,则在ANSI中可能显示为“1 2 3”
,字符串的其余部分将丢失
在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());
}
有一些优秀的库可以编写漂亮且功能丰富的xlsx Excel文件。例如:
当我打开Excel文件时,它会提醒xls文件格式和扩展名不匹配…因为您正在编写的不是实际的xls文件,而是纯文本文件。仅因为您使用了.xls文件扩展名,它就不能成为有效的Excel文件。您需要一些东西来创建实际的xls文件。但是请注意。Excel会尝试打开此文件,而不是ext文件为*.xls,它失败,然后尝试将其作为制表符分隔的*.txt文件打开。您应该将文件名更改为“d:\\test.txt”
以保持一致性。或者您可以使用逗号而不是制表符保存为*.csv格式。因此,无法将列表控件直接写入excel文件?必须使用ODBC?也许.csv是最佳选择!非常感谢大家:)嗨,Barmak。非常感谢!非常有效!感谢!应该提到msg.format(\T(“%s\T%s\T%s\n”)是UB。@zett42为什么是UB?CString
不是C风格的字符串。你应该调用buff0.GetString()
等等,以获得指向以零结尾的字符数组的指针。尽管CString
被设计为与C风格字符串二进制兼容,但这不是(据我所知)记录。编辑,添加(LPCTSTR)
CString的强制转换