A friend asked me how to call the office program without any version. The following is my answer:
If you use the com reference method to operate the Office Components in the C # project, version dependencies seem to be positive, especially when the number of parameters of the same function in different office versions is different.
For Question 1:
The method that I can think of and tried is not to directly reference the Office COM component in the project, but to call the office COM component through reflection, which should solve the version problem.
The basic steps are as follows. Only the backbone code is displayed, which is incomplete. I use word to convert Doc to htm. The same is true for other office programs:
Object m_word;
Type m_wordtype;
M_wordtype = type. gettypefromprogid ("word. Application", false );
If (m_wordtype = NULL)
Throw new applicationexception ("An error occurred while obtaining the word type ");
Try
{
M_word = activator. createinstance (m_wordtype );
M_wordtype.getproperty ("visible"). setvalue (m_word, true, null); // display the started word
}
Catch (exception ERR)
{
Throw new applicationexception ("failed to create a word instance:" + err. Message );
}
Object documents, document;
Documents = m_wordtype.getproperty ("documents"). getvalue (m_word, null );
Document = documents. getType (). invokemember ("open", bindingflags. invokemethod, null, documents, new object [] {filename}); // note the parameters of the method passed through object [].
Document. getType (). invokemember ("saveas", bindingflags. invokemethod, null, document, new object [] {newfilename, 8}); // There are some office constants. You need to query the office to find the specific value, for example, 8 represents the HTM format.
Document. GetType (). invokemember ("close", bindingflags. invokemethod, null, document, new object [] {}); // close the currently opened document
M_wordtype.invokemember ("quit", bindingflags. invokemethod, null, m_word, new object [] {}); // exit the word Program
System. runtime. interopservices. Marshal. releasecomobject (m_word); // release com reference