当前位置: 首页 > news >正文

How To: Create A Word Document In Powershell – Part 1 – Opening The Document, Writing Some Text, Usi

If you’re in the business of extracting data from disparate systems and presenting that in reports, then you’ll know how time-consuming (and frankly boring) it can be to format that data into tables or formats suitable for said report. Well, if your data is accessible via Powershell then this is the set of blogs for you! I’ll be writing a multi-part series on creating and manipulating Word documents in Powershell so that you can start to automate those tedious tasks and improve the consistency of your documents!


Table of Contents

  1. Opening the Word Document, Writing Some Text, Using Styles
  2. Adding and Manipulating Tables, Adding Images
  3. Document Properties, Table of Contents, Changing Page Properties
  4. Moving around the Document

Use a Template, or create everything on the fly?

It can be tempting, once you get to the end of this blog, to think“Ah great, now I can create an entire Word document directly in Powershell”and I get that completely – I had the same thought the first time I started working with this. However, there are two big reasons why I’d advise against it:

  1. It’s an awful lot of Powershell – adding all of the repeatable pieces of your document as part of the Powershell can make your script look very busy, and any modifications require you to pick through the Powershell and find the specific piece you need to update
  2. You end up repeating a lot of code! We should all be trying to reduce the amount of repeated code in our scripts; it’s inefficent, and making changes to one piece of code requires you to change all like pieces of code to maintain consistency.

Because of those reasons, I prefer to start with a templated file that sets the key components that are in every document created using the process – a title page, the table of contents, maybe (depending on the use case) text that is consistent regardless of the specifics in the document. Therefore, although I might add examples below on adding elements I include in templates the bulk will be assuming you’re also using a template.

Opening the Word document

Before we can do anything else, we need to open Word and the document we want to modify. All manipulation with word uses theWord.ApplicationComObject and so we don’t need to install or import any modules.

$word = New-Object -ComObject Word.Application #If you're starting with a blank document $doc = $word.Documents.Add() #If you're starting with a templated document $doc = $word.Documents.Open([Path to File])

TIP: If you want to see the changes that are being made to the document live, then just add this line as well:

$word.visible = $true

Setting the “Cursor”

Now that we’ve got our Word document and it’s open, we need to be able to start creating text inside it – and just like working with Word traditionally, we need to set our “cursor” location.

There are a number of different ways you can do this, depending on the complexity of your requirements and if you’re working with a template or not, but for the purpose of this we’re going to assume you want to start at the beginning of the document – and so we’re going to create our cursor at the default location:

$text = $word.Selection

Styles and Text

The$textobject is going to be our most used on throughout this series, as we move our “cursor” through the document, and below you can see it in action:

$text.style = "Heading 1" $text.TypeText("This is Heading 1") $text.TypeParagraph() $text.style = "Body Text" $text.TypeText("This is a section of text immediately under Heading 1. This might be where you add some dynamically generated information") $text.TypeParagraph() $text.style = "Heading 2" $text.TypeText("This is Heading 2") $text.TypeParagraph()

There’s a couple of different things going on here, so let me explain each property:

  • $text.stylesets the style of the current selection to one of your existing predefined styles; I’ve chosen to use the default ones you get in Word, but you may have your own pre-defined styles to use – if so, just use the name of them.
  • $text.TypeTextdoes what it suggest it does – it types text! Just enter whatever text you want to be typed into the page here, and it will go ahead and do it.
  • $text.TypeParagraphis the same as pressing Enter or Return on your keyboard; it will start a new paragraph

Before I start typing text, I explicitly set the Style – this will depend on your specific styles and whatever the ‘Style to use next’ is set to, but I like to do this as a method of ensuring the document is styled exactly how I expect it to.

And that’s it! You’ll now have the beginnings of a Word document. In the next part where we tackle tables I’ll also show how you might use that to present information collected from an external source, such as an API. Below is a full script to achieve everything I’ve talked about in this post – make sure you keep a hold of this, as you’re going to be using it in the following parts:

$word = New-Object -ComObject Word.Application $word.visible = $true #If you're starting with a blank document $doc = $word.Documents.Add() $text = $word.Selection $text.style = "Heading 1" $text.TypeText("This is Heading 1") $text.TypeParagraph() $text.style = "Body Text" $text.TypeText("This is a section of text immediately under Heading 1. This might be where you add some dynamically generated information") $text.TypeParagraph() $text.style = "Heading 2" $text.TypeText("This is Heading 2") $text.TypeParagraph() $doc.SaveAs([Path To Save File To]) $doc.Close $word.Quit
http://www.jsqmd.com/news/1098758/

相关文章:

  • Kimi LeetCode 3425. 最长特殊路径 Python3实现
  • 低查重AI写教材攻略:精选5款AI工具,轻松搞定教材写作难题!
  • GNSS数据处理新手必看:手把手教你读懂RINEX 3.04钟差文件(CLK)里的关键信息
  • django文件对象是什么?
  • Highcharts有版权吗?
  • 对称加密算法的混淆层(S盒)密码学指标详细介绍
  • TVA在具身智能全栈能力体系中的关键作用(6)
  • 限峰功率最大熵定理的理论推导和MATLAB仿真实现(P124302075刘家隆)
  • php里直接塞CSS代码?别傻了,这招让加载快如闪电
  • VMware虚拟机安装Ubuntu Linux:从零搭建开发环境的完整指南
  • TVA:连接数字与物理世界的智能底座(3)
  • 北方高寒矿区专网通信搭建要点,适配低温、粉尘、防爆严苛工况
  • 基于YOLOv8的船舶检测分类系统:从模型训练到部署的完整实践
  • 第十六篇:商业模式重塑——告别数据垄断,拥抱能力订阅
  • YOLOv9的RepNCSPELAN4模块拆解:从代码到结构图,手把手理解这个新‘C3’
  • 新能源车逆市涨价,燃油车持续降价,车市怎么突然分化了?
  • 30N06-ASEMI通用 60V 中低压 Trench MOS管
  • Dify零基础七日实战:从部署到API发布,手把手掌握LLM应用开发
  • 如何用Taskt实现零代码办公自动化:免费RPA工具完整指南
  • 3分钟终极指南:为Windows免费换上macOS专业鼠标指针
  • C++容器——string的基础实现(下)
  • 极低成本 AI 服务:独立开发者的多模型混合路由与流量网关设计
  • STM32学习笔记【25.ADC】
  • 如何快速掌握浏览器资源嗅探:猫抓Cat-Catch扩展的终极完整指南
  • AI渐进编程之五:给 Agent 穿上动力装甲——SIADOS 状态转移方法
  • 二、Prometheus 安装和配置
  • CAN一致性-容错测试--CAN_H与CAN_L短路容错性测试(bus off)
  • 【安卓程序】古诗500首卡片式-墨韵诗笺 · 部署与优化指南
  • 告别云服务器!用旧手机+Debian+AidLux,5分钟搭建你的移动AI开发环境
  • TVA在具身智能产业化体系的落地案例详解(2)