VSTO開髮指南(VB版) 第二章 Office解決方案介紹

来源:https://www.cnblogs.com/xiehaofeng/archive/2020/02/03/12255131.html
-Advertisement-
Play Games

實例2.1 通過控制台實現對Excel的自動化處理 書本第32頁 註:添加兩個引用: 第一個:程式集—框架—“System.Windows.Forms 4.0.0.0”第二個:程式集—擴展—“Microsoft.Office.Interop.Excel 14.0.0.0” 程式清單2.1通過控制台程 ...


實例2.1 通過控制台實現對Excel的自動化處理 書本第32頁

註:添加兩個引用:

第一個:程式集—框架—“System.Windows.Forms 4.0.0.0
第二個:程式集—擴展—“Microsoft.Office.Interop.Excel 14.0.0.0”

程式清單2.1通過控制台程式對Excel自動化處理

Imports Excel = Microsoft.Office.Interop.Excel

Module Module1

  Private exitXL As Boolean = False
  Dim WithEvents myExcelApp As Excel.Application

  Sub Main()

    myExcelApp = New Excel.Application
    myExcelApp.Visible = True
    myExcelApp.StatusBar = "Hello World"
    myExcelApp.Workbooks.Add()

    While exitXL = False
      System.Windows.Forms.Application.DoEvents()
    End While

  End Sub

  Private Sub myExcelApp_SheetBeforeDoubleClick(ByVal sheet _
    As Object, ByVal target As Excel.Range, ByRef cancel _
    As Boolean) Handles myExcelApp.SheetBeforeDoubleClick

    exitXL = True

  End Sub

End Module

實例代碼:

Imports Excel = Microsoft.Office.Interop.Excel
Module Module1

    Private exitXL As Boolean = False
    Dim WithEvents myExcelApp As Excel.Application '有這句需添加引用“Microsoft.Office.Interop.Excel 14.0.0.0”
    Sub Main()
        myExcelApp = New Excel.Application
        myExcelApp.Visible = True
        myExcelApp.StatusBar = "Hello World"
        myExcelApp.Workbooks.Add()
        While exitXL = False
            System.Windows.Forms.Application.DoEvents() '有這句需添加引用“System.Windows.Forms 4.0.0.0”
        End While
    End Sub

    Private Sub myExcelApp_SheetBeforeDoubleClick(ByVal sheet _
      As Object, ByVal target As Excel.Range, ByRef cancel _
      As Boolean) Handles myExcelApp.SheetBeforeDoubleClick
        exitXL = True
    End Sub
End Module
'**************************************************************************
'*雙擊單元格Office控制權會轉回到自動化程式事件處理中,
'*若沒有System.Windows.Forms.Application.DoEvents(),控制台視窗將自動關閉,
'*System.Windows.Forms.Application.DoEvents()方法可以使窗體處理其他事件,
'*所以窗體能夠進行重繪。不至於出現假死現象。
'**************************************************************************

實例效果:

 實例2.2 wiki文本表示形式 書本第33頁

  程式清單2.2 表2.1的wiki文本表示形式

||Property or Method||Name||Return Type||
||Property||Application||Application||
||Property||Autoload||Boolean||
||Property||Compiled||Boolean||
||Property||Creator||Int32||
||Method||Delete||Void||
||Property||Index||Int32||
||Property||Installed||Boolean||
||Property||Name||String||
||Property||Parent||Object||
||Property||Path||String||

實例2.3 將文本文件中的wiki形式的文本以表格的形式輸出到Word中 書本37頁

 程式清單2.3 完整的WordWiki實現

Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Imports Office = Microsoft.Office.Core
Imports Word = Microsoft.Office.Interop.Word

Module Module1
  Sub Main(ByVal args As String())

    Dim theApplication As New Word.Application
    theApplication.Visible = True
    Dim theDocument As Word.Document
    theDocument = theApplication.Documents.Add()

    Dim reader As TextReader
    reader = New System.IO.StreamReader(args(0))

    Dim separators(1) As String
    separators(0) = "||"
    Dim rowCount As Integer = 0
    Dim columnCount As Integer = 0

    ' Read rows and calculate number of rows and columns
    Dim rowList As New System.Collections.Generic.List(Of String)
    Dim row As String = reader.ReadLine()
    While row IsNot Nothing
      rowCount += 1
      rowList.Add(row)

      ' If this is the first row,
      ' calculate the number of columns
      If rowCount = 1 Then
        Dim splitHeaderRow As String() = _
          row.Split(separators, StringSplitOptions.None)

        ' Ignore the first and last separator
        columnCount = splitHeaderRow.Length - 2
      End If

      row = reader.ReadLine()
    End While

    ' Create a table
    Dim range As Word.Range = theDocument.Range()
    Dim table As Word.Table = range.Tables.Add(range, _
      rowCount, columnCount)

    ' Populate table
    Dim columnIndex As Integer = 1
    Dim rowIndex As Integer = 1

    For Each r As String In rowList
      Dim splitRow As String() = r.Split(separators, _
        StringSplitOptions.None)

      For columnIndex = 1 To columnCount
        Dim cell As Word.Cell = table.Cell(rowIndex, columnIndex)
        cell.Range.Text = splitRow(columnIndex)
      Next
      rowIndex += 1
    Next

    ' Format table
    table.Rows(1).Range.Bold = 1
    table.AutoFitBehavior( _
      Word.WdAutoFitBehavior.wdAutoFitContent)

    ' Wait for input from the command line before exiting
    System.Console.WriteLine("Table complete.")
    System.Console.ReadLine()

    ' Quit without saving changes
    theApplication.Quit(False)
  End Sub
End Module

實例代碼:

Imports System.Collections.Generic '預設
Imports System.Text  '預設
Imports System.IO '預設
Imports Office = Microsoft.Office.Core '添加引用“Microsoft Office 14.0 Object Library 2.5
Imports Word = Microsoft.Office.Interop.Word '添加引用"Microsoft.Office.Interop.word 14.0.0.0"

Module Module1
    Sub Main(ByVal args As String())

        Dim theApplication As New Word.Application '定義word程式
        theApplication.Visible = True '使word程式可視
        Dim theDocument As Word.Document '定義word文檔
        theDocument = theApplication.Documents.Add() '為程式添加word文檔

        Dim reader As TextReader  '定義Txt文本讀取器
        reader = New System.IO.StreamReader(My.Application.Info.DirectoryPath & "/test.txt") '實例化讀取文本介面,My.Application.Info.DirectoryPath指的是本程式的\bin\Debug目錄

        Dim separators(1) As String  '定義分隔符字元串
        separators(0) = "||"  '為分隔符變數賦值
        Dim rowCount As Integer = 0     '定義行數
        Dim columnCount As Integer = 0  '定義列數

        ' 讀取行並計算行數和列數
        Dim rowList As New System.Collections.Generic.List(Of String) '定義字元串型的列表集對象
        Dim row As String = reader.ReadLine() '讀取文本存儲器中的一行
        While row IsNot Nothing  '讀取行沒有到結尾
            rowCount += 1        '讀取下一行
            rowList.Add(row)    '將所讀取的一行文本存儲在列表集對象中

            ' 如果這是第一行,就計算列數
            If rowCount = 1 Then
                Dim splitHeaderRow As String() = row.Split(separators, StringSplitOptions.None) 'StringSplitOptions.None,就是分開的數組元素包括空元素
                columnCount = splitHeaderRow.Length - 2   ' 忽略第一和最後一個分隔符
            End If
            row = reader.ReadLine()
        End While

        ' 在word中創建一個表
        Dim range As Word.Range = theDocument.Range() '定義文檔單元格
        Dim table As Word.Table = range.Tables.Add(range, rowCount, columnCount) '創建一個rowCount行columnCount列的表格

        ' 操作word中所創建的表
        Dim columnIndex As Integer = 1
        Dim rowIndex As Integer = 1

        For Each r As String In rowList
            Dim splitRow As String() = r.Split(separators, StringSplitOptions.None)  'StringSplitOptions.None,就是分開的數組元素包括空元素
            For columnIndex = 1 To columnCount
                Dim cell As Word.Cell = table.Cell(rowIndex, columnIndex) '\bin\Debug目錄中test.txt文件中的結尾不能有多餘的空行,不然會提示超出索引範圍而出現錯誤
                cell.Range.Text = splitRow(columnIndex)
            Next
            rowIndex += 1
        Next

        ' 格式化表格
        table.Rows(1).Range.Bold = 1
        table.AutoFitBehavior(Word.WdAutoFitBehavior.wdAutoFitContent) 'AutoFitBehavior()方法的作用就是以某種方法調整表格,ord.WdAutoFitBehavior.wdAutoFitContent表示表格根據內容來調節

        ' 退出前等待命令輸入
        System.Console.WriteLine("Table complete.")
        System.Console.ReadLine()

        ' 沒有保存更改而退出
        theApplication.Quit(False)
    End Sub
End Module

test.txt文檔中的內容

||Property or Method||Name||Return Type||
||Property||Application||Application||
||Property||Autoload||Boolean||
||Property||Compiled||Boolean||
||Property||Creator||Int32||
||Method||Delete||Void||
||Property||Index||Int32||
||Property||Installed||Boolean||
||Property||Name||String||
||Property||Parent||Object||
||Property||Path||String||

實例效果:

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、前言 從研究生開始到工作半年,陸續在接觸MCU SOC這些以CPU為核心的控制器,但由於專業的原因一直對CPU的內部結構和工作原理一知半解。今天從一篇博客中打破一直以來的盲區。特此聲明,本文設計思想及代碼均源於如下博文,這裡僅用於自己學習記錄,以及分享心得之用。 簡易CPU的設計和實現_阡飛陌- ...
  • 這篇文章主要講解實現線程的方式到底有幾種?以及實現 Runnable 介面究竟比繼承 Thread 類實現線程好在哪裡? 實現線程是併發編程中基礎中的基礎,因為我們必須要先實現多線程,才可以繼續後續的一系列操作。所以本文就先從併發編程的基礎如何實現線程開始講起。 實現線程的方式到底有幾種?我們接下來 ...
  • 簡介 Python是一種跨平臺的電腦程式設計語言。是一種面向對象的動態類型語言,最初被設計用於編寫自動化腳本(shell),隨著版本的不斷更新和語言新功能的添加,越多被用於獨立的、大型項目的開發。 Anaconda 是一個基於 Python 的數據處理和科學計算平臺,它已經內置了許多非常有用的第三 ...
  • 大綱 一.什麼是Hash?什麼是HashMap? 二.HashMap的內部實現機制 1.HashMap基本元素 ①DEFAULT_INITIAL_CAPACITY&MAXIMUM_CAPACITY ②DEFAULT_LOAD_FACTOR&loadFactor ③size&threshold 2.H ...
  • th:href="@{/static/css/style.css}" th:src="@{/static/js/thymeleaf.js}" index.html <head> <meta charset="UTF-8"> <title>首頁</title> <link rel="styleshee ...
  • 網上的教程大都是手動通過protoc編譯, 比較難用 給當前工程添加"Google.Protobuf"和"Grpc.Tools"的引用(通過nuget), 然後添加proto文件, 編輯.csproj文件 <Project Sdk="Microsoft.NET.Sdk"> <PropertyGrou ...
  • 微信公眾號: "Dotnet9" ,網站: "Dotnet9" ,問題或建議: "請網站留言" , 如果對您有所幫助: "歡迎贊賞" 。 閱讀導航 1. 本文背景 2. 代碼實現 3. 本文參考 4. 源碼 1. 本文背景 同上篇文章《少量代碼設計一個登錄界面》,本篇介紹另一種登錄界面設計風格。 2 ...
  • 這是在ASP.NET Core 3.X中使用Serilog.AspNetCore系列文章的第四篇文章:。 1. "第1部分 使用Serilog RequestLogging減少日誌詳細程度" 2. "第2部分 使用Serilog記錄所選的終結點屬性" 3. "第3部分 使用Serilog.AspN ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...