下面的代碼使用一個現有的統計圖Excel文件,加載這個文件,設置某一項的值和統計圖的表示方式,然後保存到另一個Excel文件裡。如果是VS2005+Office2003,也可以選擇使用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 = m_objExcel.Workbooks.Open("z:\\Book11.xls", m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, m_objOpt, 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, m_objOpt, m_objOpt, Excel.XlSaveAsAccessMode.xlNoChange,
m_objOpt, m_objOpt, 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();
}
源Excel文件中的統計圖:
經過代碼處理後保存的統計圖: