序
刚工作那会,用的还是VC++6.0,要做大量数据采集,然后写Excel文件。
那时候不像现在有很多工具类可以直接写Excel。
最开始直接写txt文件,用tab进行空格,然后用Excel打开的时候,就自行分割了。
但是对于有些数据要隔开不同的位置进行填写,计算结果,排版就非常麻烦了。
过后通过MFC加载模块,导出excel的接口,调用并读写excel;
记得当时导出的类很多,有时候使用并不是很方便,好像各种invoke函数。
然后为了方便使用,对其进行封装通用的写数据接口。
后来无意中在网上看见一个C#写Excel的实现,我改成C++了,希望能对大家有所帮助。
当时放在我的CSDN上,准备写一些东西,后来太忙也觉得储备不够,就放弃了。
代码
今天在这里再贴出来,供大家分享。
#include <stdio.h>
#include <string.h>
typedef unsigned short ushort;
class ExcelWriter
{
private:
FILE *pf;
void WriteArray(const void *value, ushort len)
{
if (pf)
fwrite(value, 1, len, pf);
}
public:
ExcelWriter() { pf = 0; }
~ExcelWriter() { if (pf) fclose(pf); }
void WriteCell(ushort row, ushort col, const char *value)
{
ushort iLen = (ushort)strlen(value);
ushort clData[] = { 0x0204, ushort(8 + iLen), row, col, 0, iLen };
WriteArray(clData, 12);
WriteArray(value, iLen);
}
void WriteCell(ushort row, ushort col, int value)
{
ushort clData[] = { 0x027E, 10, row, col, 0 };
WriteArray(clData, 10);
int iValue = (value << 2) | 2;
WriteArray(&iValue, 4);
}
void WriteCell(ushort row, ushort col, double value)
{
ushort clData[] = { 0x0203, 14, row, col, 0 };
WriteArray(clData, 10);
WriteArray(&value, 8);
}
void WriteCell(ushort row, ushort col)
{
ushort clData[] = { 0x0201, 6, row, col, 0x17 };
WriteArray(clData, 10);
}
bool BeginWrite(const char *fileName)
{
pf = fopen(fileName, "wb+");
printf("pf=%p\n", pf);
if (!pf) return false;
ushort clBegin[] = { 0x0809, 0x08, 0x0, 0x10, 0x0, 0x0 };
WriteArray(clBegin, 12);
return true;
}
void EndWrite()
{
ushort clEnd[] = { 0x0A, 0x0 };
WriteArray(clEnd, 4);
fclose(pf);
pf = 0;
}
};
int main(int argc, char **argv)
{
ExcelWriter writer;
writer.BeginWrite("./demo.xls");
writer.WriteCell(0, 0, "ExcelWriter Demo");
writer.WriteCell(1, 0, "int");
writer.WriteCell(1, 1, 10);
writer.WriteCell(2, 0, "double");
writer.WriteCell(2, 1, 1.5);
writer.WriteCell(3, 0, "empty");
writer.WriteCell(3, 1);
writer.EndWrite();
return 0;
}
总结
归根结底也是对二进制文件操作,然后有对应的格式。(嵌入式平台也可以直接使用)
如果觉得我写的还不错的话,求赞,求关注哦!(^▽^)