C#操作Word實現插入圖表

引用dll

using Word = Microsoft.Office.Interop.Word;//操作word
using Excel = Microsoft.Office.Interop.Excel;//操作excel

初始化操作Word

                Object Nothing = System.Reflection.Missing.Value;
                //Directory.CreateDirectory("C:/CNSI");  //創建文件所在目錄
                //string name = "CNSI_" + DateTime.Now.ToLongDateString() + ".doc";
                object filename = path;  //文件保存路徑
                //創建Word文檔
                Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
                Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
在Excel中創建圖表,然後複製到Word中
Excel.Application eApp = new Excel.Application();//創建Excel進程  
                eApp.Visible = false;//設置Excel可見  
                Excel.Workbook book = eApp.Workbooks.Add();//增加一個workboo  
                Excel.Worksheet sheet = eApp.Worksheets[1];//獲取第一個Worksheet  
                Excel.Range range = sheet.get_Range("A1", "D2");//獲取A1到D2範圍內的Range  
                                                                //向表格中插入數據  
                range.Cells[1][1] = "姓名";
                range.Cells[1][2] = "成績";
                range.Cells[2][1] = "張三";
                range.Cells[2][2] = "89";
                range.Cells[3][1] = "李四";
                range.Cells[3][2] = "100";
                range.Cells[4][1] = "王五";
                range.Cells[4][2] = "95";

                //插入圖表À  
                Excel.Chart xlChart = book.Charts.Add();
                //設置圖表源  
                xlChart.SetSourceData(range);
                //拷貝表格  
                Word.Range wdRange = WordDoc.Range(); ;
                //拷貝Excel中某個sheet數據到word
                wdRange.SetRange(wdRange.End, wdRange.End + 1);
                xlChart.ChartArea.Copy();
                wdRange.Paste(); 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章