Coder Social home page Coder Social logo

node-xlsx's Introduction

node-xlsx

npm version npm total downloads npm monthly downloads npm license build status

Features

Straightforward excel file parser and builder.

  • Relies on SheetJS xlsx module to parse/build excel sheets.
  • Built with TypeScript for static type checking with exported types along the library.

Install

npm install node-xlsx --save
# or
pnpm add node-xlsx

Quickstart

Parse an xlsx file

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

// Parse a buffer
const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/myFile.xlsx`));
// Parse a file
const workSheetsFromFile = xlsx.parse(`${__dirname}/myFile.xlsx`);

Build an xlsx file

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
var buffer = xlsx.build([{name: 'mySheetName', data: data}]); // Returns a buffer

Custom column width

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const sheetOptions = {'!cols': [{wch: 6}, {wch: 7}, {wch: 10}, {wch: 20}]};

var buffer = xlsx.build([{name: 'mySheetName', data: data}], {sheetOptions}); // Returns a buffer

Spanning multiple rows A1:A4 in every sheets

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const data = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const range = {s: {c: 0, r: 0}, e: {c: 0, r: 3}}; // A1:A4
const sheetOptions = {'!merges': [range]};

var buffer = xlsx.build([{name: 'mySheetName', data: data}], {sheetOptions}); // Returns a buffer

Spanning multiple rows A1:A4 in second sheet

import xlsx from 'node-xlsx';
// Or var xlsx = require('node-xlsx').default;

const dataSheet1 = [
  [1, 2, 3],
  [true, false, null, 'sheetjs'],
  ['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
  ['baz', null, 'qux'],
];
const dataSheet2 = [
  [4, 5, 6],
  [7, 8, 9, 10],
  [11, 12, 13, 14],
  ['baz', null, 'qux'],
];
const range = {s: {c: 0, r: 0}, e: {c: 0, r: 3}}; // A1:A4
const sheetOptions = {'!merges': [range]};

var buffer = xlsx.build([
  {name: 'myFirstSheet', data: dataSheet1},
  {name: 'mySecondSheet', data: dataSheet2, options: sheetOptions},
]); // Returns a buffer

Beware that if you try to merge several times the same cell, your xlsx file will be seen as corrupted.

  • Using Primitive Object Notation Data values can also be specified in a non-abstracted representation.

Examples:

const rowAverage = [[{t: 'n', z: 10, f: '=AVERAGE(2:2)'}], [1, 2, 3]];
var buffer = xlsx.build([{name: 'Average Formula', data: rowAverage}]);

Refer to xlsx documentation for valid structure and values:

Troubleshooting

This library requires at least node.js v10. For legacy versions, you can use this workaround before using the lib.

npm i --save object-assign
Object.prototype.assign = require('object-assign');

Contributing

Please submit all pull requests the against master branch. If your unit test contains javascript patches or features, you should include relevant unit tests. Thanks!

Available scripts

Script Description
start Alias of test:watch
test Run mocha unit tests
test:watch Run and watch mocha unit tests
lint Run eslint static tests
compile Compile the library
compile:watch Compile and watch the library

Authors

Olivier Louvignes

Copyright and license

Apache License 2.0

Copyright (C) 2012-2014  Olivier Louvignes

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.

Except where noted, this license applies to any and all software programs and associated documentation files created by the Original Author and distributed with the Software:

Inspired by SheetJS gist examples, Copyright (c) SheetJS.

node-xlsx's People

Contributors

alvinthedeveloper avatar caiguanhao avatar cuspymd avatar downeystark avatar ecole1295 avatar giano avatar gregkapustin avatar jhvst avatar kkhiga avatar kokogino avatar lifubang avatar liurunchao avatar mayeaux avatar mgcrea avatar raacker avatar rajandhinoja avatar rprovost avatar sai1919 avatar sunbeams001 avatar vied12 avatar youngerheart avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-xlsx's Issues

Bug in workbook sheet writer - Date convertion

in helpers.js the buildExcelDate function returns the wrong date in the case that !is1904
It should read:
const buildExcelDate = (value, is1904) => {
if(is1904) value+=1462;
const epoch = Date.parse(value);
return (epoch - originDate) / (24 * 60 * 60 * 1000)
};

ERROR:can't find end of central dire

hello,here is my test code:
var xlsx = require('node-xlsx');
var path = require('path');
var fs = require('fs');

//var obj = xlsx.parse(path.join(process.cwd(),'resources/history.xls')); // parses a file

var obj2 = xlsx.parse(fs.readFileSync(path.join(process.cwd(),'resources/history.xls'))); // parses a buffer

setInterval(function(){
console.log('');
},1000)

parse error!

If there are two or more format in a cell , it will parse error with the cell value!

why the data in xlsx is Integer,but throuth the xlsx.parse,the data change into Float

In my xlsx file the data is Integer . but through the xlsx.parse method , the data change into a Float.
How can I resolve the problem?

My node-xlsx version "node-xlsx": "^0.7.4";
The origin data:
image

The code:
const workSheetsFromFile = xlsx.parse(${__dirname}/../../${fileurl}); console.log(workSheetsFromFile[0].data);

The xlsx.parse data:
[ [ 'T(℃)', 'R(KΩ)' ],
[ -40, 3225.4617 ],
[ -39, 3026.3501 ],
[ -38, 2839.6504 ],
[ -37, 2664.7295 ],
[ -36, 2500.9521 ],
[ -35, 2347.6975 ],
[ -34, 2204.3501 ],
[ -33, 2070.3164 ],
[ -32, 1945.0251 ],
[ -31, 1827.9241 ],
[ -30, 1718.49 ],
[ -29, 1614.1907 ] ]

Working with xls files

Is it possible to parse XLS files with this plugin? I have been able to parse XLSX so far but no luck with the XLS files.

multiple sheets

If I issue multiple JSON in "build", e.g.

var buffer = xlsx.build([{name: "mySheetName", data: data}, {name: "mySheetName1", data: data}]);

Should I be able to create mutiple sheets in the workbook? I tried but only one sheet is created. I just want to confirm if this is the case.

Plot

Hello,
Can we also do plotting in addition to inserting data ?

Thanks

Cannot resolve module 'fs'

build.js:667 ./~/xlsx/xlsx.js
Module not found: Error: Cannot resolve module 'fs' in D:\workSpace\git\vue-xlsx\node_modules\xlsx

I need help

I use it to exports excel but got an error ,I need you help ,thanks you very much.

var excelData = _xlsx2.default.write(workBook, Object.assign({}, defaults, o
^
TypeError: undefined is not a function

TypeError: Cannot call method 'asText' of null

This is the error I am getting when I am parsing a excel file

xlsx/xlsx.js:35
s = zip.file('docProps/core.xml').asText();
^
TypeError: Cannot call method 'asText' of null
at Context.xlsx (xlsx/xlsx.js:35:38)
at Object.module.exports.parse (D:\office work\projects\cricplayer_admin\nod
e_modules\node-xlsx\lib\node-xlsx.js:21:20)
at Object. (D:\office work\projects\cricplayer_admin\node-excel-t
ry.js:4:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)

can't parse excel

/Users/combine/epiboly/laiyehong/app/node_modules/node-xlsx/node_modules/xlsx/xlsx.js:11555
                                default: throw 'unrecognized type ' + val.t;
                                         ^
unrecognized type stub

i don't know below code's feature, but i explanatory them, parse can work.

    switch(val.t){
                case 'e': continue;
                case 's': break;
                case 'b': case 'n': break;
                default: throw 'unrecognized type ' + val.t;
            }

How to apply Formatting/Style in new version ?

Till version 0.4 input was given like :

[{"value":"Name","bold":true,"formatCode":"General","autoWidth":true},"value":"Age","bold":true,"formatCode":"General","autoWidth":true}]

So it was easy to format. But since v0.5 , it takes data in Array of Array form like :

[["Name","age"],["Ashu","25"]

Can't figure out how to apply style in this new format.

Error: Corrupted zip : can't find end of central directory

 Posted {"size":54272,"path":"/var/folders/7r/52ncf525795fy1pz4mtwps1m0000gn/T/68a874f48575058f0c78acfbd8b0f5fe","name":"QTL_Sample_data.xls","type":"application/vnd.ms-excel","mtime":"2014-10-16T18:37:22.655Z"}
 Error thrown for request: /test
 Error: Corrupted zip : can't find end of central directory

Getting this when I try and upload an XLS file, any suggestions?

Javascript heap out of memory (Node)

Javascript heap out of memory when trying to build a XLSX for a modest set of 133 rows of 3 columns in Node. The error is caused by buildSheetFromMatrix.

Streaming Read?

Hi, from the documentation, it is not clear (to me). Does this lib support streaming reads of sheets in an Excel workbook? I want to work with potentially huge sheets of data without loading all into memory.

Unsupported file 117 and 97

I may be missing something simple, but how can I determine if the xls or xlsx is valid? Parsing is working great for valid files, but invalid files are crashing my node.js / sails.js application with a "Unsupported file 117" or 97 error when I run XLSX.readFile(//myUploadedfile) on an invalid file. How can I catch this error? Can I get a return from xlsx to determine if a file is a valid xls or xlsx prior to trying to parse it? Do I need to first determine it is valid outside of XLSX, if so any suggestions on method? Again, I apologize if I missed something in the documentation. If not included, it could be a good beginner item to add to documentation.

TypeError:Cannot set property length of [Object Object] which has only a getter

I used it to parse xls successfully.
however when I use it to parse xls documents again,it shows the message.
TypeError:Cannot set property length of [Object Object] which has only a getter
at dbcs_d (node-xlsx\node_modules\xlsx\dist\cpexcel.js:989:20)
at Object.decode (node-xlsx\node_modules\xlsx\dist\cpexcel.js:1197:40)
at _gc2 (node-xlsx\node_modules\xlsx\xlsx.js:28:24)
at Buffer.ReadShift as read_shift
at parse_ShortXLUnicodeString (node-xlsx\node_modules\xlsx\xlsx.js:3082:21)
at Object.parse_Font as f
at slurp (node-xlsx\node_modules\xlsx\xlsx.js:9229:11)
at parse_workbook (node-xlsx\node_modules\xlsx\xlsx.js:9350:15)
at parse_xlscfb (node-xlsx\node_modules\xlsx\xlsx.js:9827:27)
at Object.readSync as read

file open issues

i keep getting this warning when i try to pen xlsx file generated by node-xlsx ,
Excel could not open mySheetName (1).xlsx because some content is unreadable. Do you want to open and repair this workbook?

Can not parse the excel date to javascript date type

Hey, guys, here is a problem I got: There is a column in my xlsx file that is to describe time. And if I input a '#8:30', then it can parse it right because the value is a string. But once I input '08:30', firstly the excel will change the value in to a date type, and then node-xlsx will parse it into a decimal type, now the value become 0.3541666666666667. I can't figure it out. I will appreciate it if someone can tell me how to deal with it. Thanks.

TypeError: Object function Object() { [native code] } has no method 'assign'

It's wonderful to use your tool on Windows10! But today I got a TypeError when using centos7 with nodejs, this is the ErrorCode below. I hope you can fix it :) Thanks!
at Object.build (/root/projects/czg/node_modules/node-xlsx/lib/index.js:46:57) at repl:1:19 at REPLServer.self.eval (repl.js:110:21) at repl.js:249:20 at REPLServer.self.eval (repl.js:122:7) at Interface.<anonymous> (repl.js:239:12) at Interface.emit (events.js:95:17) at Interface._onLine (readline.js:203:10) at Interface._line (readline.js:532:8) at Interface._ttyWrite (readline.js:761:14)

Merge cells in sheets

As the option parameter is common to the build, they apply to all sheets ; which is a problem toward merging of cells : I'd like to merge cells in a sheet but not the others.

Thx for the package it's great

Issue with same data record in subsequent row

If I have the same data on the subsequent row it gets ignored and I end up in a cell lesser than what actually is. For Example if I have the data like in below grid it just returns me [[a,b,c,d]] instead of [[a,b,c,c,e]]

image

undefined key?

the latest version will add an undefined key to the data,but the version 0.5.1 won't.

Date formatted columns lose value in JSON?

Hi there! Is there a way to read in data from an Excel sheet so that it retains the date? When I try to read in date-formatted columns (such as 11/4/14) it gives it a value of 41947 in the JSON object.

Cannot find module 'jszip

I try to use this package by npm install node-xlsx and the i import the package
import xlsx from 'node-xlsx';

but when i run the app it gives

Uncaught Error: Cannot find module 'jszip' install.js:78

then i install jszip by
import xlsx from 'jszip';
but it gives the same error

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.