|
我们的程序里面如何调用office2010呢,就是在我们的程序里面如何进行办公自动化开发,在我们的程序里面自动生成excel与word
核心代码如下,基于VS2010创建一个空白CLR工程,插入下列C++代码,直接编译执行之。
//.h file code:
using namespace System;
using namespace System::Collections::Generic;
//引用office 2010
namespace Excel = Microsoft::Office::Interop::Excel;
namespace Word = Microsoft::Office::Interop::Word;
//创建引用类 Account
public ref class Account
{
public:
property int ID;
property double Balance;
};
声明程序接口与方法
public ref class Program
{
static void Main(array<System::String^> ^args);
private:
static void AnonymousMethod1(System::Object ^account, System::Object ^cell);
public:
static void DisplayInExcel(IEnumerable<Account^> ^accounts, Action<Account^, Excel::Range^> ^DisplayFunc);
};
//.cpp file code:
using namespace System;
using namespace System::Collections::Generic;
namespace Excel = Microsoft::Office::Interop::Excel;
namespace Word = Microsoft::Office::Interop::Word;
//开始执行程序
void Program::Main(array<System::String^> ^args)
{
var ^checkAccounts = gcnew List<Account^> { gcnew Account { ID = 345, Balance = 541.27 }, gcnew Account { ID = 123, Balance = -127.44 } };
//设置自定义处理规则
DisplayInExcel(checkAccounts, AnonymousMethod1);
var ^word = gcnew Word.Application();
word->Visible = true;
word->Documents->Add();
word->Selection->PasteSpecial(Link: true, DisplayAsIcon: true);
}
void Program::AnonymousMethod1(System::Object ^account, System::Object ^cell)
{
cell->Value2 = account->ID;
cell->get_Offset(0, 1)->Value2 = account->Balance;
if (account->Balance < 0)
{
cell->Interior->Color = 255;
cell->get_Offset(0, 1)->Interior->Color = 255;
}
}
//打开并创建excel
void Program::DisplayInExcel(IEnumerable<Account^> ^accounts, Action<Account^, Excel::Range^> ^DisplayFunc)
{
var ^xl = gcnew Excel::Application();
xl->Workbooks->Add();
xl->Visible = true;
xl->Cells[1, 1] = "ID";
xl->Cells[1, 2] = " Balance";
xl->Cells[2, 1]->Select();
for each (var ^ac in accounts)
{
DisplayFunc(ac, xl->ActiveCell);
xl->ActiveCell->get_Offset(1, 0)->Select();
}
xl->get_Range("A1:B3")->Copy();
xl->Columns[1]->AutoFit();
xl->Columns[2]->AutoFit();
}
执行效果如下
生成excel 2010
生成 word 2010
(责任编辑:admin) |