Convert Figma logo to code with AI

Ziv-Barber logoofficegen

Standalone Office Open XML files (Microsoft Office 2007 and later) generator for Word (docx), PowerPoint (pptx) and Excell (xlsx) in javascript. The output is a stream.

2,648
471
2,648
198

Top Related Projects

7,241

A pure PHP library for reading and writing word processing documents

Open XML SDK by Microsoft

4,192

Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.

Quick Overview

Officegen is a Node.js library that allows users to generate Microsoft Office documents programmatically. It supports the creation of PowerPoint presentations, Excel spreadsheets, and Word documents without requiring Microsoft Office to be installed on the system.

Pros

  • Cross-platform compatibility, as it doesn't require Microsoft Office installation
  • Supports multiple Office document types (PowerPoint, Excel, Word)
  • Easy to use with a simple API
  • Actively maintained with regular updates

Cons

  • Limited formatting options compared to native Office applications
  • May not support all advanced features of Office documents
  • Performance can be slower for large or complex documents
  • Documentation could be more comprehensive

Code Examples

Creating a PowerPoint presentation:

const officegen = require('officegen');
const fs = require('fs');

const pptx = officegen('pptx');

const slide = pptx.makeNewSlide();
slide.addText('Hello World!', { x: 100, y: 50, font_size: 56 });

const out = fs.createWriteStream('example.pptx');
pptx.generate(out);

Generating an Excel spreadsheet:

const officegen = require('officegen');
const fs = require('fs');

const xlsx = officegen('xlsx');

const sheet = xlsx.makeNewSheet();
sheet.name = 'My Sheet';

sheet.data[0] = ['Name', 'Age'];
sheet.data[1] = ['John Doe', 30];
sheet.data[2] = ['Jane Smith', 25];

const out = fs.createWriteStream('example.xlsx');
xlsx.generate(out);

Creating a Word document:

const officegen = require('officegen');
const fs = require('fs');

const docx = officegen('docx');

docx.createP().addText('Hello World!', { bold: true, underline: true });

const out = fs.createWriteStream('example.docx');
docx.generate(out);

Getting Started

To use Officegen in your Node.js project:

  1. Install the package:

    npm install officegen
    
  2. Import the library in your JavaScript file:

    const officegen = require('officegen');
    
  3. Create a document of the desired type:

    const pptx = officegen('pptx');
    // or
    const xlsx = officegen('xlsx');
    // or
    const docx = officegen('docx');
    
  4. Add content to your document using the appropriate methods.

  5. Generate the file:

    const fs = require('fs');
    const out = fs.createWriteStream('output.pptx');
    pptx.generate(out);
    

Competitor Comparisons

7,241

A pure PHP library for reading and writing word processing documents

Pros of PHPWord

  • Specifically designed for PHP, offering seamless integration with PHP projects
  • Extensive documentation and active community support
  • Supports a wider range of document formats, including OOXML, ODF, and RTF

Cons of PHPWord

  • Limited to PHP environment, less versatile than officegen's Node.js platform
  • May have a steeper learning curve for developers not familiar with PHP
  • Performance can be slower for large document generation compared to officegen

Code Comparison

PHPWord:

$phpWord = new \PhpOffice\PhpWord\PhpWord();
$section = $phpWord->addSection();
$section->addText('Hello World!');
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$objWriter->save('helloWorld.docx');

officegen:

let docx = officegen('docx');
let pObj = docx.createP();
pObj.addText('Hello World!');
docx.generate(fs.createWriteStream('helloWorld.docx'));

Both libraries offer straightforward methods to create simple documents. PHPWord's syntax is more verbose, reflecting its comprehensive feature set, while officegen provides a more concise approach. The choice between them often depends on the developer's preferred language and specific project requirements.

Open XML SDK by Microsoft

Pros of Open-XML-SDK

  • More comprehensive support for Office Open XML formats
  • Better performance for large document processing
  • Stronger type safety and compile-time checks

Cons of Open-XML-SDK

  • Steeper learning curve due to more complex API
  • Limited to .NET environment
  • Requires more code for simple operations

Code Comparison

officegen example:

var docx = officegen('docx');
var pObj = docx.createP();
pObj.addText('Simple text.');

Open-XML-SDK example:

using (WordprocessingDocument doc = WordprocessingDocument.Create(path, WordprocessingDocumentType.Document))
{
    MainDocumentPart mainPart = doc.AddMainDocumentPart();
    mainPart.Document = new Document(new Body(new Paragraph(new Run(new Text("Simple text.")))));
}

The officegen library offers a more straightforward API for simple document creation, while Open-XML-SDK provides more granular control over document structure at the cost of verbosity. Open-XML-SDK is better suited for complex document manipulation and processing large files efficiently, whereas officegen excels in quick, simple document generation across multiple platforms.

4,192

Easily generate and modify .docx files with JS/TS with a nice declarative API. Works for Node and on the Browser.

Pros of docx

  • More focused on Word document generation, potentially offering more specialized features
  • Active development with frequent updates and contributions
  • Comprehensive documentation and examples available

Cons of docx

  • Limited to Word documents, while officegen supports multiple Office formats
  • May have a steeper learning curve for users familiar with officegen's API
  • Potentially less flexible for generating other Office file types

Code Comparison

officegen:

var officegen = require('officegen');
var docx = officegen('docx');
var pObj = docx.createP();
pObj.addText('Hello World!');

docx:

import { Document, Paragraph, TextRun } from "docx";
const doc = new Document();
const paragraph = new Paragraph({
  children: [new TextRun("Hello World!")]
});
doc.addParagraph(paragraph);

Both libraries allow for creating Word documents with simple text content. officegen uses a more straightforward API, while docx offers a more object-oriented approach. The choice between them may depend on the specific project requirements, desired features, and the developer's familiarity with each library's syntax and structure.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

officegen

Creating Office Open XML files (Word, Excel and Powerpoint) for Microsoft Office 2007 and later without external tools, just pure Javascript. officegen should work on any environment that supports Node.js including Linux, OSX and Windows. officegen also supporting PowerPoint native charts objects with embedded data.

npm version dependencies devDependencies Build Status Join the chat at https://gitter.im/officegen/Lobby Backers on Open Collective Sponsors on Open Collective

Officegen logo Microsoft Office logo

Contributors:

This project exists thanks to all the people who contribute.

Getting Started:

Microsoft Powerpoint logo Microsoft Word logo Microsoft Excel logo

Officegen features overview:

  • Generating Microsoft PowerPoint document (.pptx file):
    • Create PowerPoint document with one or more slides.
    • Support both PPT and PPS.
    • Can create native charts.
    • Add text blocks.
    • Add images.
    • Can declare fonts, alignment, colors and background.
    • You can rotate objects.
    • Support shapes: Ellipse, Rectangle, Line, Arrows, etc.
    • Support hidden slides.
    • Support automatic fields like date, time and current slide number.
    • Support speaker notes.
    • Support slide layouts.
  • Generating Microsoft Word document (.docx file):
    • Create Word document.
    • You can add one or more paragraphs to the document and you can set the fonts, colors, alignment, etc.
    • You can add images.
    • Support header and footer.
    • Support bookmarks and hyperlinks.
  • Generating Microsoft Excel document (.xlsx file):
    • Create Excel document with one or more sheets. Supporting cells with either numbers or strings.

Installation:

$ npm install officegen

Microsoft PowerPoint basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty PowerPoint object:
let pptx = officegen('pptx')

// Let's add a title slide:

let slide = pptx.makeTitleSlide('Officegen', 'Example to a PowerPoint document')

// Pie chart slide example:

slide = pptx.makeNewSlide()
slide.name = 'Pie Chart slide'
slide.back = 'ffff00'
slide.addChart(
  {
    title: 'My production',
    renderType: 'pie',
    data:
	[
      {
        name: 'Oil',
        labels: ['Czech Republic', 'Ireland', 'Germany', 'Australia', 'Austria', 'UK', 'Belgium'],
        values: [301, 201, 165, 139, 128,  99, 60],
        colors: ['ff0000', '00ff00', '0000ff', 'ffff00', 'ff00ff', '00ffff', '000000']
      }
    ]
  }
)

// Let's generate the PowerPoint document into a file:

return new Promise((resolve, reject) => {
  let out = fs.createWriteStream('example.pptx')

  // This one catch only the officegen errors:
  pptx.on('error', function(err) {
    reject(err)
  })

  // Catch fs errors:
  out.on('error', function(err) {
    reject(err)
  })

  // End event after creating the PowerPoint file:
  out.on('close', function() {
    resolve()
  })

  // This async method is working like a pipe - it'll generate the pptx data and put it into the output stream:
  pptx.generate(out)
})

Since that officegen is using node.js events you can also create a document directly into a http respons stream:

const officegen = require('officegen')
const http = require('http')

/**
 * This is a simple web server that response with a PowerPoint document.
 */
http.createServer(function(req, res) {
  // We'll send a generated on the fly PowerPoint document without using files:
  if (req.url == '/') {
    // Create an empty PowerPoint object:
    let pptx = officegen('pptx')

    // Let's create a new slide:
    var slide = pptx.makeNewSlide()

    slide.name = 'Hello World'

    // Change the background color:
    slide.back = '000000'

    // Declare the default color to use on this slide:
    slide.color = 'ffffff'

    // Basic way to add text string:
    slide.addText('Created on the fly using a http server!')

    //
    // Let's generate the PowerPoint document directly into the response stream:
    //

    response.writeHead(200, {
      'Content-Type':
        'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'Content-disposition': 'attachment filename=out.pptx'
    })

	// Content types related to Office documents:
    // .xlsx   application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    // .xltx   application/vnd.openxmlformats-officedocument.spreadsheetml.template
    // .potx   application/vnd.openxmlformats-officedocument.presentationml.template
    // .ppsx   application/vnd.openxmlformats-officedocument.presentationml.slideshow
    // .pptx   application/vnd.openxmlformats-officedocument.presentationml.presentation
    // .sldx   application/vnd.openxmlformats-officedocument.presentationml.slide
    // .docx   application/vnd.openxmlformats-officedocument.wordprocessingml.document
    // .dotx   application/vnd.openxmlformats-officedocument.wordprocessingml.template
    // .xlam   application/vnd.ms-excel.addin.macroEnabled.12
    // .xlsb   application/vnd.ms-excel.sheet.binary.macroEnabled.12

    // This one catch only the officegen errors:
    pptx.on('error', function(err) {
      res.end(err)
    })

    // Catch response errors:
    res.on('error', function(err) {
      res.end(err)
    })

    // End event after sending the PowerPoint data:
    res.on('finish', function() {
      res.end()
    })

    // This async method is working like a pipe - it'll generate the pptx data and pass it directly into the output stream:
    pptx.generate(res)
  } else {
    res.end('Invalid Request!')
  } // Endif.
}).listen(3000)

Where to go from here?

Microsoft Word basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty Word object:
let docx = officegen('docx')

// Officegen calling this function after finishing to generate the docx document:
docx.on('finalize', function(written) {
  console.log(
    'Finish to create a Microsoft Word document.'
  )
})

// Officegen calling this function to report errors:
docx.on('error', function(err) {
  console.log(err)
})

// Create a new paragraph:
let pObj = docx.createP()

pObj.addText('Simple')
pObj.addText(' with color', { color: '000088' })
pObj.addText(' and back color.', { color: '00ffff', back: '000088' })

pObj = docx.createP()

pObj.addText('Since ')
pObj.addText('officegen 0.2.12', {
  back: '00ffff',
  shdType: 'pct12',
  shdColor: 'ff0000'
}) // Use pattern in the background.
pObj.addText(' you can do ')
pObj.addText('more cool ', { highlight: true }) // Highlight!
pObj.addText('stuff!', { highlight: 'darkGreen' }) // Different highlight color.

pObj = docx.createP()

pObj.addText('Even add ')
pObj.addText('external link', { link: 'https://github.com' })
pObj.addText('!')

pObj = docx.createP()

pObj.addText('Bold + underline', { bold: true, underline: true })

pObj = docx.createP({ align: 'center' })

pObj.addText('Center this text', {
  border: 'dotted',
  borderSize: 12,
  borderColor: '88CCFF'
})

pObj = docx.createP()
pObj.options.align = 'right'

pObj.addText('Align this text to the right.')

pObj = docx.createP()

pObj.addText('Those two lines are in the same paragraph,')
pObj.addLineBreak()
pObj.addText('but they are separated by a line break.')

docx.putPageBreak()

pObj = docx.createP()

pObj.addText('Fonts face only.', { font_face: 'Arial' })
pObj.addText(' Fonts face and size.', { font_face: 'Arial', font_size: 40 })

docx.putPageBreak()

pObj = docx.createP()

// We can even add images:
pObj.addImage('some-image.png')

// Let's generate the Word document into a file:

let out = fs.createWriteStream('example.docx')

out.on('error', function(err) {
  console.log(err)
})

// Async call to generate the output file:
docx.generate(out)

Where to go from here?

Microsoft Excel basic usage example:

const officegen = require('officegen')
const fs = require('fs')

// Create an empty Excel object:
let xlsx = officegen('xlsx')

// Officegen calling this function after finishing to generate the xlsx document:
xlsx.on('finalize', function(written) {
  console.log(
    'Finish to create a Microsoft Excel document.'
  )
})

// Officegen calling this function to report errors:
xlsx.on('error', function(err) {
  console.log(err)
})

let sheet = xlsx.makeNewSheet()
sheet.name = 'Officegen Excel'

// Add data using setCell:

sheet.setCell('E7', 42)
sheet.setCell('I1', -3)
sheet.setCell('I2', 3.141592653589)
sheet.setCell('G102', 'Hello World!')

// The direct option - two-dimensional array:

sheet.data[0] = []
sheet.data[0][0] = 1
sheet.data[1] = []
sheet.data[1][3] = 'some'
sheet.data[1][4] = 'data'
sheet.data[1][5] = 'goes'
sheet.data[1][6] = 'here'
sheet.data[2] = []
sheet.data[2][5] = 'more text'
sheet.data[2][6] = 900
sheet.data[6] = []
sheet.data[6][2] = 1972

// Let's generate the Excel document into a file:

let out = fs.createWriteStream('example.xlsx')

out.on('error', function(err) {
  console.log(err)
})

// Async call to generate the output file:
xlsx.generate(out)

Where to go from here?

Support:

Examples:

  • make_pptx.js - Example how to create PowerPoint 2007 presentation and save it into file.
  • make_xlsx.js - Example how to create Excel 2007 sheet and save it into file.
  • make_docx.js - Example how to create Word 2007 document and save it into file.
  • pptx_server.js - Example HTTP server that generating a PowerPoint file with your name without using files on the server side.

The official officegen Google Group:

officegen Google Group

The officegen Slack team:

Slack

Plans for the next release:

Trello

:coffee: The source code:

The project structure:

  • office/index.js - The main file.
  • office/lib/ - All the sources should be here.
    • basicgen.js - The generic engine to build many type of document files. This module providing the basicgen plugins interface for all the document generator. Any document generator MUST use this plugins API.
    • docplug.js - The document generator plugins interface - optional engine to create plugins API for each document generator.
    • msofficegen.js - A template basicgen plugin to extend the default basicgen module with the common Microsoft Office stuff. All the Microsoft Office based document generators in this project are using this template plugin.
    • genpptx.js - A document generator (basicgen plugin) to create a PPTX/PPSX document.
    • genxlsx.js - A document generator (basicgen plugin) to create a XLSX document.
    • gendocx.js - A document generator (basicgen plugin) to create a DOCX document.
    • pptxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Powerpoint based features.
    • docxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Word based features.
    • xlsxplg-*.js - docplug based plugins for genpptx.js ONLY to implement Excel based features.
  • officegen/test/ - All the unit tests.
  • Gruntfile.js - Grunt scripts.

Code documentations:

To create the jsdoc documentation:

grunt jsdoc

External dependencies:

This project is using the following awesome libraries/utilities/services:

  • archiver
  • jszip
  • lodash
  • xmlbuilder

How to add new features:

The easiest way to add new features is by using the officegen internal plugins system.

Credit:

  • Created by Ziv Barber in 2013.
  • For creating zip streams i'm using 'archiver' by cmilhench, dbrockman, paulj originally inspired by Antoine van Wel's zipstream.

Contributors:

This project exists thanks to all the people who contribute.

Backers:

Thank you to all our backers! 🙏 [Become a backer]

Sponsors:

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

NPM DownloadsLast 30 Days