#include "excel.h"
BOOL CTestExcelCtrl::saveexcel(LPCTSTR str)
{
// TODO: Add your dispatch handler code here
_Application app;
Workbooks books;//工作簿的集合
_Workbook book; //工作簿
Worksheets sheets;//工作表的集合
_Worksheet sheet;//工作表
Range range; //单元格区域
Font font;
Range cols;
COleVariant covOptional((long)DISP_E_PARAMNOTFOUND,VT_ERROR);//填充参数
if(!app.CreateDispatch("Excel.Application"))//启动一个excel对象
{
return FALSE;
}
books=app.GetWorkbooks(); //获得工作簿的集合对象
book= books.Add(covOptional);//添加一个工作簿
sheets=book.GetSheets(); //获得工作表的集合对象
sheet=sheets.GetItem(COleVariant((short)1));//获得一个工作表对象
range=sheet.GetRange(COleVariant("A1"),COleVariant("A1"));//获得操作的单元格区域
range.SetValue2(COleVariant(str));//设置单元格的值
font=range.GetFont();// 获得字体对象
font.SetBold(COleVariant((short)TRUE));
range=sheet.GetRange(COleVariant("A2"),COleVariant("A2"));//获得操作的单元格区域
range.SetFormula(COleVariant("=RAND()*100000"));//插入设置的公式
range.SetNumberFormat(COleVariant("$0.00"));//设置格式
//选择A:A列设置宽度为自动适应
cols=range.GetEntireColumn();
cols.AutoFit();
app.SetVisible(TRUE);
//设置状态为用户可控制
app.SetUserControl(TRUE);
//自动保存创建的excel文件
/*
void SaveAs(
const VARIANT& Filename, const VARIANT& FileFormat, const VARIANT& Password,
const VARIANT& WriteResPassword, const VARIANT& ReadOnlyRecommended, const VARIANT& CreateBackup,
long AccessMode, const VARIANT& ConflictResolution, const VARIANT& AddToMru,
const VARIANT& TextCodepage, const VARIANT& TextVisualLayout, const VARIANT& Local);
*/
book.SaveAs(
COleVariant("d://excel.xls"),covOptional,covOptional,
covOptional,covOptional,covOptional,
(long)0,covOptional,covOptional,
covOptional,covOptional,covOptional);
app.Quit();
if(books)
books.ReleaseDispatch();
if(book)
book.ReleaseDispatch();
if(sheets)
sheets.ReleaseDispatch();
if(sheet)
sheet.ReleaseDispatch();
if(app)
app.ReleaseDispatch();
return TRUE;
}
vc操作excel填充单元格的值
最新推荐文章于 2020-11-18 11:42:57 发布