如何使用VSTO自動將Excel中的圖表復制到Word
阿新 • • 發佈:2017-09-07
rto log ocx ins started 沒有 sub mes 如何
如何使用VSTO自動將Excel中的圖表復制到Word
原文地址:https://code.msdn.microsoft.com/How-to-copy-Chart-in-Excel-a29f9029
該項目說明如何使用VSTO自動復制Excel中的圖表
介紹
有些客戶經常在MSDN論壇上提出這個問題。 但在MSDN畫廊中沒有現有的樣本。 所以如果有樣品,可以幫助客戶解決問題。
客戶證據:
http://social.msdn.microsoft.com/Forums/en-US/isvvba/thread/21a2fd18-d850-40d9-9d87-122bbaf9369d
http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/8d94da85-a95f-41c0-b7ec-6bf34fd0e151
創建項目
在Visual Studio 2013中打開項目(VBNETExportExcelChartToWord.vbproj)並構建它。
VB代碼:
1 Module Module1 2 Sub Main(args As String()) 3 Try 4 Dim appPath As String = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) 5 Dim excelFile As String= appPath & Convert.ToString("\TestExcel.xlsx") 6 Dim wordFile As String = appPath & Convert.ToString("\TestDoc.docx") 7 ExportChartDataToWord(excelFile, wordFile) 8 Console.WriteLine("Chart exported to word document successfully") 9 Console.ReadLine()10 Catch ex As Exception 11 Console.WriteLine(ex.Message) 12 End Try 13 End Sub 14 Sub ExportChartDataToWord(excelFile As String, wordFile As String) 15 Dim objExcelApp As Microsoft.Office.Interop.Excel._Application = New Microsoft.Office.Interop.Excel.Application() 16 objExcelApp.Visible = False 17 Dim workbook As Microsoft.Office.Interop.Excel._Workbook = objExcelApp.Workbooks.Open(excelFile) 18 Dim worksheet As Microsoft.Office.Interop.Excel._Worksheet = DirectCast(workbook.Sheets(1), Microsoft.Office.Interop.Excel.Worksheet) 19 Dim charObj As Microsoft.Office.Interop.Excel.ChartObject = worksheet.ChartObjects("Chart 1") 20 Dim objWordApp As Microsoft.Office.Interop.Word._Application = New Microsoft.Office.Interop.Word.Application() 21 If objWordApp Is Nothing Then 22 Console.WriteLine("Word could not be started. Check that your office installation and project references are correct.") 23 Return 24 End If 25 objWordApp.Visible = False 26 Dim objDoc As Microsoft.Office.Interop.Word._Document = objWordApp.Documents.Open(wordFile) 27 charObj.Chart.ChartArea.Copy() 28 objDoc.Application.Selection.PasteSpecial() 29 ‘Save the doc 30 objDoc.Save() 31 ‘Close the open docs and workbooks 32 objWordApp.Documents.Close() 33 objWordApp.Quit() 34 objExcelApp.Workbooks.Close() 35 objExcelApp.Quit() 36 End Sub 37 End Module
1.此示例從Excel文件中復制圖表對象內容,然後使用VSTO方式將其粘貼到Word文檔中。
2.在執行示例之前,將TestDoc.docx和TestExcel.xlsx文件復制到可執行位置。
3.運行可執行文件VBNETExportExcelChartToWord.exe,這將會將圖表內容復制到名為TestDoc.docx的單詞文檔中?
4.打開word文檔並驗證其內容。
如何使用VSTO自動將Excel中的圖表復制到Word