Export js data to word as docx format

To export data to a Word document, you can use the following methods:

  1. Use third-party JavaScript libraries such as docx.js, jsPDF, etc., which contain APIs for creating and exporting Word documents.
  2. Using a combination of HTML and CSS styles, render the data into an HTML template and then save it as a Word document using your browser's built-in "Save As" feature.
  3. Use server-side technologies, such as Node.js, PHP, etc., to generate Word documents on the server and then provide them to the client for download.

Here is a simple example using the docx.js library:

  1. Introduce the docx.js library into the HTML file:
<script src="https://unpkg.com/docx.js/dist/docx.js"></script>
  1. Create a JavaScript object with data:
const data = {
    
    
  name: "John Smith",
  email: "[email protected]",
  phone: "123-456-7890"
};
  1. Create a blank Word document using docx.js:
const doc = new docx.Document();
  1. Add data to the document:
doc.addSection({
    
    
  children: [
    new docx.Paragraph("Name: " + data.name),
    new docx.Paragraph("Email: " + data.email),
    new docx.Paragraph("Phone: " + data.phone)
  ]
});
  1. Save the document as a .docx file using Node.js:
const fs = require("fs");
const path = require("path");

docx.Packer.toBuffer(doc).then(buffer => {
    
    
  const filePath = path.join(__dirname, "output.docx");
  fs.writeFileSync(filePath, buffer);
});

This is a simple example, using docx.js you can create more complex documents and decorate them with elements such as styles and images.

Guess you like

Origin blog.csdn.net/weixin_42317757/article/details/132656473
Recommended