`
tcspecial
  • 浏览: 897757 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

C++ 导出excel

阅读更多

   在C++下导出excel还是件比较棘手的,虽说目前有很多方式导出,但是都不太方便. 没有像java下强大的poi直接导出二进制格式的excel文件.

 

     1. QT下通过com组件调用excel

pro文件添加: LIBS += -lqaxserver -lqaxcontainer

        获取com api文档:

QAxObject* excel = new QAxObject("excel.Application");  // wps 下 ET.Application
QFile outfile("d:/excel_doc.html");
QTextStream out( &outfile );
outfile.open( IO_WriteOnly | IO_Translate );
QString doc = excel->generateDocumentation();
out<<doc;
outfile.close();

 

    缺点: excel导出严重依赖系统程序,QT com api虽说封装的很彻底,但是仍然很晦涩,使用起来不太方便. 仅仅设置单元格背景色这个功能在API找了半天,还是没解决

 

   2. 第三方开源库

   C++下几个开源库,大多数都是收费的(libxl等). libxls库不错免费,但是在windows下编译很不方便,libExcel也是采用libxls的核心库编译的,可以很方便在windows下编译,但是只能在vs05及以上版本编译,而且不支持中文.

 

   3. excel特定html格式导出

   excel可以打开特定格式的txt,html, 其中txt的表现形式太弱,只能简单显示单元格数据,无法设置格式

bool writeTxtToExcel()
{
	QFile data("d:/test.xls");
	if(!data.open(QFile::WriteOnly | QFile::Truncate)) 
	{
		return false;
	}

	QTextStream out(&data);
	QString tt1=QString::fromLocal8Bit("外国");
	QString tt2=QString::fromLocal8Bit("人文关怀");
	out<<tt1<<"\t"<<tt2<<"\t"<<"\n"; //每个单元格以\t分隔,每行以\n分隔
	out<<"25\t"<<"26\t";
	data.close();

	return true;
}

 

   至于html格式,我们可以预先定义好一个excel模块文档,后另存为*.htm格式就行了; 打开代码发现真正数据部分就是一个Table,我们只要构建一个有数据的Table字符串,然后替换模块文档就可以了

 

<table width="665" border="0" cellpadding="0" cellspacing="0" style='width:498.75pt;border-collapse:collapse;table-layout:fixed;'>
<col width="72" span="4" style='width:54.00pt;'/>
<col width="137" style='mso-width-source:userset;mso-width-alt:4384;width:102.75pt;'/>
<col width="121" style='mso-width-source:userset;mso-width-alt:3872;width:90.75pt;'/>
<col width="119" style='mso-width-source:userset;mso-width-alt:3808;width:89.25pt;'/>
<tr height="19" style='height:14.25pt;'>
<td class="xl26" height="19" width="72" style='height:14.25pt;width:54.00pt;'/>
<td class="xl26" width="72" style='width:54.00pt;' x:num="3.472222222222222e-003">0:05</td>
<td class="xl26" width="72" style='width:54.00pt;' x:num="6.9444444444444441e-003">0:10</td>
</tr>
<tr height="19" style='height:14.25pt;'>
<td class="xl24" height="19" style='height:14.25pt;' x:str>1A1</td>
<td class="xl23"/>
<td class="xl23"/>
</tr>
</table>

   缺点: 由于要预先生成模板,格式比较固定,修改起来也比较困难, 但是不依赖任何组件,使用起来效果也还不错

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics