[Post this article: http://www.cnblogs.com/dahuzizyd/archive/2006/11/28/excel_csharp_2.html]
The following code uses an existing statistical graph Excel file to load this file, set the value of a certain item and the expression of the statistical graph, and then save it to another Excel file. For vs2005 + office2003, you can use Visual Studio Tools for office.
Excel. Application m_objexcel = NULL;
Excel. _ workbook m_objbook = NULL;
Excel. _ chart m_objchart = NULL;
Excel. chartgroup m_objchartgroup = NULL;
Excel. Series m_objseries = NULL;
Object m_objopt = system. reflection. Missing. value;
Try
{
M_objexcel = new excel. Application ();
M_objbook = compile ("Z: \ book11.xls", m_objopt, merge, merge, m_objopt, m_objopt, merge, m_objopt );
M_objchart = (Excel. _ chart) m_objexcel.charts.get_item (1 );
M_objchart.barshape = excel. xlbarshape. xlcylinder;
M_objchartgroup = (Excel. chartgroup) m_objchart.chartgroups (1 );
M_objseries = (Excel. Series) m_objchartgroup.seriescollection (1 );
M_objseries.values = 456;
M_objexcel.displayalerts = false;
M_objbook.saveas ("Z: \ book2.xls", m_objopt, m_objopt,
M_objopt, Excel. xlsaveasaccessmode. xlnochange,
M_objopt, m_objopt );
}
Catch (exception ex)
{
MessageBox. Show (ex. Message );
}
Finally
{
M_objbook.close (m_objopt, m_objopt, m_objopt );
M_objexcel.workbooks.close ();
M_objexcel.quit ();
System. runtime. interopservices. Marshal. releasecomobject (m_objbook );
System. runtime. interopservices. Marshal. releasecomobject (m_objexcel );
M_objbook = NULL;
M_objexcel = NULL;
GC. Collect ();
This. Close ();
}
Statistical charts in the source Excel file:
Statistical charts saved after code processing: