最近经常用EXCEL导出报表,上网搜索了一下,整理了一下CB操作EXCEL的操作,以作留念
1:启动Excel
Variant vExcelApp, vSheet, Range;
Variant vExcelApp = Variant::CreateObject("Excel.Application"); //
vExcelApp.OlePropertySet("Visible", false);//隐藏Excel界面
vExcelApp.OlePropertyGet("Workbooks").OleFunction("Add", 1); // 新增工作区
vSheet = vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("Sheets", 1);//操作这个工作表
2:退出Excel
vExcelApp.OlePropertyGet("ActiveWorkbook").OleFunction("SaveAs", "c://2.xls");//保存
vExcelApp.OleFunction("Quit");//退出
vSheet = Unassigned;
vExcelApp = Unassigned;
//不保存直接退出
vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertySet("Saved", true);
vExcelApp.OleFunction("Quit");
3:对齐
Range.OlePropertySet("VerticalAlignment", 3);
Range.OlePropertySet("HorizontalAlignment", 3); //2=居左 3=居中
4:赋值
vSheet.OlePropertyGet("Cells", 3, i + 2).OlePropertySet("Value", gdbill[i].c_str());
5:操作字体
vSheet.OlePropertyGet("Cells",1, j + 1).OlePropertyGet("Font").OlePropertySet("Bold", true);
font-bold, Italic,size, name,color(rgb)
6:行高,列宽
vSheet.OlePropertyGet("Columns", 2).OlePropertySet("ColumnWidth", 25);
vExcelApp.OlePropertyGet("Rows", 1).OlePropertySet("RowHeight", 30);
8:合并单元格
char b1 = 'b' + i * 2; //b
String ra;
ra.sprintf("%c%d:%c%d", b1, 2, b1 + 1, 2);
Range = vSheet.OlePropertyGet("range", ra.c_str());
Range.OleFunction("Merge", false);
9:设置单元格背景
vInter = vSheet.OlePropertyGet( "Cells", 1, j + 1).OlePropertyGet("Interior");
vInter.OlePropertySet("ColorIndex", 15); // 灰色
vInter.OlePropertySet("Pattern", 1); // xlSolid
vInter.OlePropertySet("PatternColorIndex", -4105); // xlAutomatic
10:操纵多工作表
//生成缺省的三个工作表
vExcelApp.OlePropertyGet("Workbooks").OleFunction("Add"); // 工作表
//选择工作表1
vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("Sheets", 1).OleProcedure("Select");
vSheet1 = vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("ActiveSheet");
//选择工作表
vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("Sheets", 2).OleProcedure("Select");
vSheet2 = vExcelApp.OlePropertyGet("ActiveWorkbook").OlePropertyGet("ActiveSheet");
参考资料: