Как с помощью javascript заполнить word
Перейти к содержимому

Как с помощью javascript заполнить word

  • автор:

How to create a Word document with JavaScript

Word documents are everywhere and are used for countless tasks so you may have a requirement to support their generation from within your web application or webpage, this could include downloading a C.V from your personal site to the generation of a report based on data from within your web application that can be printed out or emailed by your client.

Goals

Create and save a Word document using only client-side vanilla/plain JavaScript.

Prerequisites

In order to complete this example you should have some basic knowledge of HTML and JavaScript.

Step 1 — Setup project

In order to concentrate on the job in hand and to get up and running as quickly as possible we are going to use CodeSandbox and their vanilla starter project.

A new CodeSandbox project can be created by opening the following link vanilla JavaScript project.

Step 2 — Install dependencies needed to create a Word document

With the project setup we can now install the two modules/dependencies needed to successfully create and save a Word document. The first package (docx) allows you to build your Word document and the second package (file-saver) gives the ability to save the document locally.

Add the two packages using the «Add Dependency» button.

Step 3 — Add a button to create our Word document

Before we start writing the code required to generate our Word documents lets add a button to the index.html file. We can then use this button to fire off the actions needed to generate the Word document.

Exit fullscreen mode

Step 4 — Create a blank Word document

From now one we will be working solely within the index.js JavaScript file, lets start by deleting everything that is currently there as this is not need.

All we will need to create a blank word document is the Document and Packer features from the docx module and the saveAs feature from file-saver module.

Exit fullscreen mode

Next add an event listener that is listening for clicks on the button we created in Step 3.

Exit fullscreen mode

Once the event listener is triggered we will call a function that will create a new instance of Document from the docx module and send this instance to a saveDocumentToFile function.

Exit fullscreen mode

The saveDocumentToFile function creates a new instance of Packer from the docx modules, Packers in docx are used to turn your JavaScript code into a .docx file. We then send our document instance to Packers toBlob function which in turn converts our instance of Document into a Blob object, a mimeType is added to the Blob and finally the Blob is sent to saveAs feature of the file-saver module which will create the file and prompt you to save or open.

Exit fullscreen mode

Clicking the ‘Generate Word Document’ button will now create and save a blank Word document.

Step 5 — Create content of the Word document

We can now start adding some content to the Word document. We will simply add a title, subtitle, two headings and a long paragraph as this will make it easier to understand once we come to start styling the document.

Exit fullscreen mode

The Word document will now look something like this

Step 6 — Style the Word document

Now that we have some content we can look at styling the document.

Firstly we will create a theme object that will hold all the information about which fonts and colours we want to use.

Exit fullscreen mode

After creating the theme object we can start creating our styles. We will create 5 styles

  • Custom Heading 1
  • Custom Heading 2
  • Custom Title
  • Custom Subtitle
  • Custom Normal

These should tie up nicely to the content that we created in Step 5.

You can learn more about styles in Microsoft Word here

Exit fullscreen mode

With our styles in place we can apply them to our content.

Exit fullscreen mode

Clicking the ‘Generate Word Document’ button now will create a Word document that look something like this

Conclusion

With the use of a couple of great packages we can easily create a nice looking Word document using solely client side JavaScript. Docx is very powerful and this article only covers the basics to get you up and running with a simple Word document.

Как с помощью js заполнить шаблон Word?

Есть готовый шаблон Word, как можно его заполнить на сайте с помощью формы в которую вводятся данные созданной на js? После заполнения формы заполненный шаблон качается с сервера.

Какая библиотека для выполнения данных задач потребуется? Если она там нужна.

  • Вопрос задан более трёх лет назад
  • 2501 просмотр
  • Facebook
  • Вконтакте
  • Twitter

В шаблоне docx пометить поля для вставки и т.д. закрыть
В вашей программе
docx — открыть как обычный архив, достать из него файл word/document.xml
Подправить заменой как обычный текст. (Сначала с помощью регулярных выражений лишние ‘<.*?>’)

Например я непосредственно в JSzip пробовал

Затем просто менять поля на ваши данные
xmlfile = xmlfile.replace(«field1», data);

word/document.xml — Положить обратно в архив

  • Facebook
  • Вконтакте
  • Twitter

Сделать это всй на стороне сервера. (Примерно тоже самое на node js, PHP . )
Здесь был показан только логика. Здесь XML упоминается только потому что так устроен docx, а вся работа идет как с обычным txt. Взять docx, распаковать как обыкновенный архив и подкоректировать как обычный текст, предварительно отмеченные поля очистить от мусора с помощью регулярных выражений
Отмеченные поля в xml выглядят примерно так: <

>, от этого можно оставить только . docx от этого не поломается.
С библотеками для docx гораздо медленнее получалось. А по такому принципу и большие табличные отчеты довольно быстро заполняются.

Using JavaScript to "Create" a Microsoft Word Document

I would like to dynamically create a document using JavaScript and then open that document in Microsoft word. Is this possible? Here is my current code:

Nisse Engström's user avatar

7 Answers 7

I’m not sure exactly what you are trying to do in your code up there but here is some information i found about accessing a word document and a table within the doc:

Microsoft Word Object Model

This object model is part of Microsoft Word (not Javascript) and it lets you «automate» word remotely from other programs (not just web pages, but any computer program).

It is primarily designed for Visual Basic, but can be accessed by Javascript from a web page — see para 2 below.

However it is a bit more tricky to use through Javascript, particularly because you cannot use visual basic constants — you need to refer to them by value. If you research this further, you will soon know what I mean by this.

So where can you find out about this Object Model?

It is all there in the Word help files if you look for it.

If you look in the Word help, under programming information, you will find the Microsoft Word Visual Basic Programming Reference.

The Word object model, which lets you do things you will need to solve your problem like:

  • Open Word
  • Open a Document in Word
  • Access the collection of Tables in that ActiveDocument.
  • Access the Rows and Cells of a given Table.

How do you access this from Javascript?

This might only be done I think through Internet Explorer (and perhaps Opera).

Here you need to learn about ActiveXObjects.

ActiveXObjects (if you do not know) are separate computer programs which enable additional functionality. There are lots of ActiveX objects on the internet.

When you install Word, this also installs an ActiveX object for automating word, giving you access to the Word Object Model.

Name already in use

office-js-docs-pr / docs / tutorials / word-tutorial.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

10 contributors

Users who have contributed to this file

  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Tutorial: Create a Word task pane add-in

In this tutorial, you’ll create a Word task pane add-in that:

  • Inserts a range of text
  • Formats text
  • Replaces text and inserts text in various locations
  • Inserts images, HTML, and tables
  • Creates and updates content controls

[!TIP] If you’ve already completed the Build your first Word task pane add-in quick start, and want to use that project as a starting point for this tutorial, go directly to the Insert a range of text section to start this tutorial.

Office connected to a Microsoft 365 subscription (including Office on the web).

[!NOTE] If you don’t already have Office, you can join the Microsoft 365 developer program to get a free, 90-day renewable Microsoft 365 subscription to use during development.

Create your add-in project

  • Choose a project type: Office Add-in Task Pane project
  • Choose a script type: JavaScript
  • What do you want to name your add-in? My Office Add-in
  • Which Office client application would you like to support? Word

Screenshot showing the prompts and answers for the Yeoman generator in a command line interface.

After you complete the wizard, the generator creates the project and installs supporting Node components.

Insert a range of text

In this step of the tutorial, you’ll programmatically test that your add-in supports the user’s current version of Word, and then insert a paragraph into the document.

Open the project in your code editor.

Open the file ./src/taskpane/taskpane.html. This file contains the HTML markup for the task pane.

Locate the <main> element and delete all lines that appear after the opening <main> tag and before the closing </main> tag.

Add the following markup immediately after the opening <main> tag.

Open the file ./src/taskpane/taskpane.js. This file contains the Office JavaScript API code that facilitates interaction between the task pane and the Office client application.

Remove all references to the run button and the run() function by doing the following:

Locate and delete the line document.getElementById(«run»).onclick = run; .

Locate and delete the entire run() function.

Within the Office.onReady function call, locate the line if (info.host === Office.HostType.Word) < and add the following code immediately after that line. Note:

  • This code adds an event handler for the insert-paragraph button.
  • The insertParagraph function is wrapped in a call to tryCatch (both functions will be added in the next step). This allows any errors generated by the Office JavaScript API layer to be handled separately from your service code.

Add the following functions to the end of the file. Note:

Your Word.js business logic will be added to the function passed to Word.run . This logic doesn’t execute immediately. Instead, it’s added to a queue of pending commands.

The context.sync method sends all queued commands to Word for execution.

The tryCatch function will be used by all the functions interacting with the workbook from the task pane. Catching Office JavaScript errors in this fashion is a convenient way to generically handle uncaught errors.

Within the insertParagraph() function, replace TODO1 with the following code. Note:

The first parameter to the insertParagraph method is the text for the new paragraph.

The second parameter is the location within the body where the paragraph will be inserted. Other options for insert paragraph, when the parent object is the body, are «End» and «Replace».

Save all your changes to the project.

Complete the following steps to start the local web server and sideload your add-in.

[!TIP] If you’re testing your add-in on Mac, run the following command in the root directory of your project before proceeding. When you run this command, the local web server starts.

To test your add-in in Word, run the following command in the root directory of your project. This starts the local web server (if it isn’t already running) and opens Word with your add-in loaded.

To test your add-in in Word on the web, run the following command in the root directory of your project. When you run this command, the local web server starts. Replace «» with the URL of a Word document on your OneDrive or a SharePoint library to which you have permissions.

In Word, if the «My Office Add-in» task pane isn’t already open, choose the Home tab, and then choose the Show Taskpane button in the ribbon to open the add-in task pane.

Screenshot displaying the Show Taskpane button highlighted in Word.

In the task pane, choose the Insert Paragraph button.

Make a change in the paragraph.

Choose the Insert Paragraph button again. Note that the new paragraph appears above the previous one because the insertParagraph method is inserting at the start of the document’s body.

Screenshot showing the Insert Paragraph button in the add-in.

In this step of the tutorial, you’ll apply a built-in style to text, apply a custom style to text, and change the font of text.

Apply a built-in style to text

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-paragraph button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-paragraph button, and add the following code after that line.

Add the following function to the end of the file.

Within the applyStyle() function, replace TODO1 with the following code. Note that the code applies a style to a paragraph, but styles can also be applied to ranges of text.

Apply a custom style to text

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the apply-style button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the apply-style button, and add the following code after that line.

Add the following function to the end of the file.

Within the applyCustomStyle() function, replace TODO1 with the following code. Note that the code applies a custom style that does not exist yet. You’ll create a style with the name MyCustomStyle in the Test the add-in step.

Save all your changes to the project.

Change the font of text

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the apply-custom-style button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the apply-custom-style button, and add the following code after that line.

Add the following function to the end of the file.

Within the changeFont() function, replace TODO1 with the following code. Note that the code gets a reference to the second paragraph by using the ParagraphCollection.getFirst method chained to the Paragraph.getNext method.

Save all your changes to the project.

If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

Be sure there are at least three paragraphs in the document. You can choose the Insert Paragraph button three times. Check carefully that there’s no blank paragraph at the end of the document. If there is, delete it.

In Word, create a custom style named «MyCustomStyle». It can have any formatting that you want.

Choose the Apply Style button. The first paragraph will be styled with the built-in style Intense Reference.

Choose the Apply Custom Style button. The last paragraph will be styled with your custom style. (If nothing seems to happen, the last paragraph might be blank. If so, add some text to it.)

Choose the Change Font button. The font of the second paragraph changes to 18 pt., bold, Courier New.

Screenshot showing the results of applying the styles and fonts defined for the add-in buttons Apply Style, Apply Custom Style, and Change font.

Replace text and insert text

In this step of the tutorial, you’ll add text inside and outside of selected ranges of text, and replace the text of a selected range.

Add text inside a range

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the change-font button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the change-font button, and add the following code after that line.

Add the following function to the end of the file.

Within the insertTextIntoRange() function, replace TODO1 with the following code. Note:

The function is intended to insert the abbreviation [«(M365)»] into the end of the Range whose text is «Microsoft 365». It makes a simplifying assumption that the string is present and the user has selected it.

The first parameter of the Range.insertText method is the string to insert into the Range object.

The second parameter specifies where in the range the additional text should be inserted. Besides «End», the other possible options are «Start», «Before», «After», and «Replace».

The difference between «End» and «After» is that «End» inserts the new text inside the end of the existing range, but «After» creates a new range with the string and inserts the new range after the existing range. Similarly, «Start» inserts text inside the beginning of the existing range and «Before» inserts a new range. «Replace» replaces the text of the existing range with the string in the first parameter.

You saw in an earlier stage of the tutorial that the insert* methods of the body object don’t have the «Before» and «After» options. This is because you can’t put content outside of the document’s body.

We’ll skip over TODO2 until the next section. Within the insertTextIntoRange() function, replace TODO3 with the following code. This code is similar to the code you created in the first stage of the tutorial, except that now you are inserting a new paragraph at the end of the document instead of at the start. This new paragraph will demonstrate that the new text is now part of the original range.

Add code to fetch document properties into the task pane’s script objects

In all previous functions in this tutorial, you queued commands to write to the Office document. Each function ended with a call to the context.sync() method which sends the queued commands to the document to be executed. But the code you added in the last step calls the originalRange.text property, and this is a significant difference from the earlier functions you wrote, because the originalRange object is only a proxy object that exists in your task pane’s script. It doesn’t know what the actual text of the range in the document is, so its text property can’t have a real value. It’s necessary to first fetch the text value of the range from the document and use it to set the value of originalRange.text . Only then can originalRange.text be called without causing an exception to be thrown. This fetching process has three steps.

Queue a command to load (that is, fetch) the properties that your code needs to read.

Call the context object’s sync method to send the queued command to the document for execution and return the requested information.

Because the sync method is asynchronous, ensure that it has completed before your code calls the properties that were fetched.

The following step must be completed whenever your code needs to read information from the Office document.

Within the insertTextIntoRange() function, replace TODO2 with the following code.

When you’re done, the entire function should look like the following:

Add text between ranges

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-text-into-range button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-text-into-range button, and add the following code after that line.

Add the following function to the end of the file.

Within the insertTextBeforeRange() function, replace TODO1 with the following code. Note:

The function is intended to add a range whose text is «Office 2019, » before the range with text «Microsoft 365». It makes an assumption that the string is present and the user has selected it.

The first parameter of the Range.insertText method is the string to add.

The second parameter specifies where in the range the additional text should be inserted. For more details about the location options, see the previous discussion of the insertTextIntoRange function.

Within the insertTextBeforeRange() function, replace TODO2 with the following code.

Replace TODO3 with the following code. This new paragraph will demonstrate the fact that the new text is not part of the original selected range. The original range still has only the text it had when it was selected.

Replace TODO4 with the following code.

Replace the text of a range

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-text-outside-range button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-text-outside-range button, and add the following code after that line.

Add the following function to the end of the file.

Within the replaceText() function, replace TODO1 with the following code. Note that the function is intended to replace the string «several» with the string «many». It makes a simplifying assumption that the string is present and the user has selected it.

Save all your changes to the project.

If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

In the task pane, choose the Insert Paragraph button to ensure that there’s a paragraph at the start of the document.

Within the document, select the phrase «Microsoft 365 subscription». Be careful not to include the preceding space or following comma in the selection.

Choose the Insert Abbreviation button. Note that » (M365)» is added. Note also that at the bottom of the document a new paragraph is added with the entire expanded text because the new string was added to the existing range.

Within the document, select the phrase «Microsoft 365». Be careful not to include the preceding or following space in the selection.

Choose the Add Version Info button. Note that «Office 2019, » is inserted between «Office 2016» and «Microsoft 365». Note also that at the bottom of the document a new paragraph is added but it contains only the originally selected text because the new string became a new range rather than being added to the original range.

Within the document, select the word «several». Be careful not to include the preceding or following space in the selection.

Choose the Change Quantity Term button. Note that «many» replaces the selected text.

Screenshot showing the results of choosing the add-in buttons Insert Abbreviation, Add Version Info, and Change Quantity Term.

Insert images, HTML, and tables

In this step of the tutorial, you’ll learn how to insert images, HTML, and tables into the document.

Define an image

Complete the following steps to define the image that you’ll insert into the document in the next part of this tutorial.

In the root of the project, create a new file named base64Image.js.

Open the file base64Image.js and add the following code to specify the Base64-encoded string that represents an image.

Insert an image

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the replace-text button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Locate the Office.onReady function call near the top of the file and add the following code immediately before that line. This code imports the variable that you defined previously in the file ./base64Image.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the replace-text button, and add the following code after that line.

Add the following function to the end of the file.

Within the insertImage() function, replace TODO1 with the following code. Note that this line inserts the Base64-encoded image at the end of the document. (The Paragraph object also has an insertInlinePictureFromBase64 method and other insert* methods. See the following «Insert HTML» section for an example.)

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-image button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-image button, and add the following code after that line.

Add the following function to the end of the file.

Within the insertHTML() function, replace TODO1 with the following code. Note:

The first line adds a blank paragraph to the end of the document.

The second line inserts a string of HTML at the end of the paragraph; specifically two paragraphs, one formatted with the Verdana font, the other with the default styling of the Word document. (As you saw in the insertImage method earlier, the context.document.body object also has the insert* methods.)

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-html button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-html button, and add the following code after that line.

Add the following function to the end of the file.

Within the insertTable() function, replace TODO1 with the following code. Note that this line uses the ParagraphCollection.getFirst method to get a reference to the first paragraph and then uses the Paragraph.getNext method to get a reference to the second paragraph.

Within the insertTable() function, replace TODO2 with the following code. Note:

The first two parameters of the insertTable method specify the number of rows and columns.

The third parameter specifies where to insert the table, in this case after the paragraph.

The fourth parameter is a two-dimensional array that sets the values of the table cells.

The table will have plain default styling, but the insertTable method returns a Table object with many members, some of which are used to style the table.

Save all your changes to the project.

If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

In the task pane, choose the Insert Paragraph button at least three times to ensure that there are a few paragraphs in the document.

Choose the Insert Image button and note that an image is inserted at the end of the document.

Choose the Insert HTML button and note that two paragraphs are inserted at the end of the document, and that the first one has the Verdana font.

Choose the Insert Table button and note that a table is inserted after the second paragraph.

Screenshot showing the results of choosing the add-in buttons Insert Image, Insert HTML, and Insert Table.

Create and update content controls

In this step of the tutorial, you’ll learn how to create Rich Text content controls in the document, and then how to insert and replace content in the controls.

[!NOTE] There are several types of content controls that can be added to a Word document through the UI, but currently only Rich Text content controls are supported by Word.js.

Before you start this step of the tutorial, we recommend that you create and manipulate Rich Text content controls through the Word UI, so you can be familiar with the controls and their properties. For details, see Create forms that users complete or print in Word.

Create a content control

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the insert-table button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the insert-table button, and add the following code after that line.

Add the following function to the end of the file.

Within the createContentControl() function, replace TODO1 with the following code. Note:

This code is intended to wrap the phrase «Microsoft 365» in a content control. It makes a simplifying assumption that the string is present and the user has selected it.

The ContentControl.title property specifies the visible title of the content control.

The ContentControl.tag property specifies an tag that can be used to get a reference to a content control using the ContentControlCollection.getByTag method, which you’ll use in a later function.

The ContentControl.appearance property specifies the visual look of the control. Using the value «Tags» means that the control will be wrapped in opening and closing tags, and the opening tag will have the content control’s title. Other possible values are «BoundingBox» and «None».

The ContentControl.color property specifies the color of the tags or the border of the bounding box.

Replace the content of the content control

Open the file ./src/taskpane/taskpane.html.

Locate the <button> element for the create-content-control button, and add the following markup after that line.

Open the file ./src/taskpane/taskpane.js.

Within the Office.onReady function call, locate the line that assigns a click handler to the create-content-control button, and add the following code after that line.

Add the following function to the end of the file.

Within the replaceContentInControl() function, replace TODO1 with the following code. Note:

  • The ContentControlCollection.getByTag method returns a ContentControlCollection of all content controls of the specified tag. We use getFirst to get a reference to the desired control.

Save all your changes to the project.

If the add-in task pane isn’t already open in Word, go to the Home tab and choose the Show Taskpane button in the ribbon to open it.

In the task pane, choose the Insert Paragraph button to ensure that there’s a paragraph with «Microsoft 365» at the top of the document.

In the document, select the text «Microsoft 365» and then choose the Create Content Control button. Note that the phrase is wrapped in tags labelled «Service Name».

Choose the Rename Service button and note that the text of the content control changes to «Fabrikam Online Productivity Suite».

Screenshot showing the results of choosing the add-in buttons Create Content Control and Rename Service.

In this tutorial, you’ve created a Word task pane add-in that inserts and replaces text, images, and other content in a Word document. To learn more about building Word add-ins, continue to the following article.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *