📗
Excel-Builder-Vanilla
Live DemoGitHub
  • Introduction
  • Cookbook
    • Creating Workbooks
    • Creating Worksheets
    • Adding data to a Worksheet
    • Sizing/Hiding Columns
    • Setting row height/style
    • Fonts and Colors
    • Formatting numbers, dates, etc
    • Alignment
    • Background Fillers
    • Formulas
    • Tables
    • Theming Tables
    • Tables Summaries
    • Adding Headers and Footers to a Worksheet
    • Inserting images into spreadsheets
Powered by GitBook
On this page
Edit on GitHub
  1. Cookbook

Formatting numbers, dates, etc

PreviousFonts and ColorsNextAlignment

Last updated 1 year ago

Formatting data is very straightforward. You create a 'formatter' and a style to take advantage of that formatter, then apply that style to any cells that need it.

If you don't know what a 'format' should contain, open Excel and go to the cell formatter.

There you should see a list of different predefined formats - choose or create as you feel necessary.

Once you have the format how you'd like, click on the 'Custom' option. This will have the code that youhad selected/setup in the 'Type' box. Just copy and paste that code into the 'format' property.

import { ExcelBuilder } from 'excel-builder-vanilla';

const artistWorkbook = createWorkbook();
const albumList = artistWorkbook.createWorksheet({ name: 'Album List' });

const currency = artistWorkbook.getStyleSheet().createFormat({
  format: '$#,##0.00',
});

// you can get the Date format directly form Excel-Builder
const date = artistWorkbook.getStyleSheet().createSimpleFormatter('date');

const originalData = [
  ['Artist', 'Album', 'Price'],
  ['Buckethead', 'Albino Slug', { value: 8.99, metadata: { style: currency.id } }],
  ['Buckethead', 'Electric Tears', { value: 13.99, metadata: { style: currency.id } }],
  ['Buckethead', 'Colma', { value: 11.34, metadata: { style: currency.id } }],
  ['Crystal Method', 'Vegas', { value: 10.54, metadata: { style: currency.id } }],
  ['Crystal Method', 'Tweekend', { value: 10.64, metadata: { style: currency.id } }],
  ['Crystal Method', 'Divided By Night', { value: 8.99, metadata: { style: currency.id } }],
];

albumList.setData(originalData);
artistWorkbook.addWorksheet(albumList);

const data = createExcelFile(artistWorkbook);
downloader('Artist WB.xlsx', data);

Note that the currency formatter could also have been done as follows:

const currencyFormat = artistWorkbook.getStyleSheet().createNumberFormatter('$#,##0.00');
const currency = artistWorkbook.getStyleSheet().createFormat({ format: currencyFormat.id });

This would allow the reuse of the currency number format by multiple formatters.