Skip to main content

Arrays of Data数据的数组

Arrays of objects are a common data format in JavaScript database connectors and other general data sources.对象数组是JavaScript数据库连接器和其他通用数据源中的常见数据格式。

Numeric datasets commonly use arrays of arrays of numbers.数字数据集通常使用数字数组的数组。

The "Data Storage" section gives a general overview of common array formats in JavaScript.“数据存储”部分概述了JavaScript中常见的数组格式。

The "Functions" section describes the related functions."Functions"部分介绍了相关功能。

Data Storage数据存储

Array of Arrays数组的数组

The spiritual equivalent of the grid in JavaScript is an array of arrays:JavaScript中网格的精神等价物是数组的数组:

SpreadsheetArray of Arrays数组的数组

`pres.xlsx` data

[
["Name", "Index"],
["Bill Clinton", 42],
["GeorgeW Bush", 43],
["Barack Obama", 44],
["Donald Trump", 45],
["Joseph Biden", 46]
]

Each array within the structure corresponds to one row. Individual data points can be read by indexing by row index and by column index:结构中的每个数组对应于一行。可以通过按行索引和按列索引进行索引来读取单个数据点:

var aoa = [
["Name", "Index"],
["Bill Clinton", 42],
["GeorgeW Bush", 43],
["Barack Obama", 44],
["Donald Trump", 45],
["Joseph Biden", 46]
];

var value_at_B4 = aoa[3][1]; // 44
var value_at_A2 = aoa[1][0]; // Bill Clinton

Arrays of Objects对象数组

Arrays of objects are commonly used to represent rows from a database:对象数组通常用于表示数据库中的行:

SpreadsheetArray of Objects

`pres.xlsx` data

[
{ Name: "Bill Clinton", Index: 42 },
{ Name: "GeorgeW Bush", Index: 43 },
{ Name: "Barack Obama", Index: 44 },
{ Name: "Donald Trump", Index: 45 },
{ Name: "Joseph Biden", Index: 46 }
]

Each object within the structure corresponds to one data row. The first row of the spreadsheet is interpreted as the header row.结构中的每个对象都对应于一个数据行。电子表格的第一行被解释为标题行。

Functions函数

The "Input" subsections describe functions that generate SheetJS worksheet objects from arrays of data.“输入”小节描述了从数据数组生成SheetJS工作表对象的函数。

The "Array Output" subsection defines functions that extract data from SheetJS worksheet objects.“数组输出”小节定义了从SheetJS工作表对象中提取数据的函数。

Example Sheet示例工作表

The live examples are based on the following worksheet:实际示例基于以下工作表:

SheetJS
12567
23678
34789
4567890

This table includes duplicate column labels ("e" and "S" appear twice in the first row) and gaps (three data rows have missing fields).该表包括重复的列标签(“e”和“S”在第一行出现两次)和间隙(三个数据行缺少字段)。

Array of Arrays Input数组输入

Create a worksheet from an array of arrays从数组创建工作表

var ws = XLSX.utils.aoa_to_sheet(aoa, opts);

XLSX.utils.aoa_to_sheet takes an array of arrays of JS values and returns a worksheet resembling the input data. Values are interpreted as follows:获取一个JS值数组数组,并返回一个类似于输入数据的工作表。数值解释如下:

  • Numbers, Booleans and Strings are stored as the corresponding types.数字、布尔值和字符串存储为相应的类型。
  • Date objects are stored as Date cells or date codes (see cellDates option)日期对象存储为日期单元格或日期代码(请参见cellDates选项)
  • Array holes and explicit undefined values are skipped.将跳过数组洞和显式undefined值。
  • null values may be stubbed (see sheetStubs and nullError options)值可能会被截断(请参阅sheetStubsnullError选项)
  • Cell objects are used as-is.单元对象按原样使用。

The function takes an options argument:该函数采用一个选项参数:

Option Name选项名称Default默认值Description描述
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认为n
sheetStubsfalseCreate cell objects of type z for null valuesnull值创建z类型的单元格对象
nullErrorfalseIf true, emit #NULL! error cells for null values如果为true,则针对null值发出#NULL!错误单元格
UTCfalseIf true, dates are interpreted using UTC methods如果为true,则使用UTC方法解释日期 **
densefalseEmit dense sheet object发出稠密工作表对象

UTC option is explained in "Dates"UTC选项在“日期”中有说明

The following live example reproduces the example worksheet:以下活动示例再现了示例工作表

Result
Loading...
Live Editor

Add data from an array of arrays to an existing worksheet将数组中的数据添加到现有工作表

XLSX.utils.sheet_add_aoa(ws, aoa, opts);

XLSX.utils.sheet_add_aoa takes an array of arrays of JS values and updates an existing worksheet object. 获取JS值的数组数组,并更新现有的工作表对象。It follows the same process as aoa_to_sheet and accepts an options argument:它遵循与aoa_to_sheet相同的过程,并接受一个选项参数:

Option Name选项名称Default默认值Description描述
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认为n
sheetStubsfalseCreate cell objects of type z for null valuesnull值创建z类型的单元格对象
nullErrorfalseIf true, emit #NULL! error cells for null values如果为true,则针对null值发出#NULL!错误单元格
originUse specified cell as starting point (see below)使用指定的单元格作为起点(见下文)
UTCfalseIf true, dates are interpreted using UTC methods如果为true,则使用UTC方法解释日期 **

UTC option is explained in "Dates"UTC选项在“日期”中有说明

origin is expected to be one of:预计是以下其中之一:

originDescription描述
(cell object)Use specified cell (cell object)使用指定的单元格(单元格对象)
(string)Use specified cell (A1-Style cell)使用指定的单元格(A1样式单元格)
(number >= 0)Start from the first column at specified row (0-indexed)从指定行的第一列开始(0索引)
-1Append to bottom of worksheet starting on first column从第一列开始追加到工作表底部
(default)Start from cell A1从单元格A1开始

The example worksheet can be built up in the following order:示例工作表可以按以下顺序构建:

Spreadsheet电子表格Operations操作
SheetJS
12567
23678
34789
4567890

0) aoa_to_sheet([[]]) creates an empty worksheet创建一个空工作表

1) sheet_add_aoa writes A1:G1 (red)写入A1:G1(红色)

2) sheet_add_aoa writes A2:B4 (blue)写入A2:B4(蓝色)

3) sheet_add_aoa writes E2:G4 (green)写入E2:G4(绿色)

4) sheet_add_aoa writes A5:G5 (yellow)写入A5:G5(黄色)

/* Start from an empty worksheet从空工作表开始 */
var ws = XLSX.utils.aoa_to_sheet([[]]);

/* First row第一行 */
XLSX.utils.sheet_add_aoa(ws, [ "SheetJS".split("") ], {origin: "A1"});

/* Write data starting at A2从A2开始写入数据 */
XLSX.utils.sheet_add_aoa(ws, [[1,2], [2,3], [3,4]], {origin: "A2"});

/* Write data starting at E2从E2开始写入数据 */
XLSX.utils.sheet_add_aoa(ws, [[5,6,7], [6,7,8], [7,8,9]], {origin:{r:1, c:4}});

/* Append row */
XLSX.utils.sheet_add_aoa(ws, [[4,5,6,7,8,9,0]], {origin: -1});
Result
Loading...
Live Editor

Array of Objects Input对象的数组输入

Create a worksheet from an array of objects从对象数组创建工作表

var ws = XLSX.utils.json_to_sheet(aoo, opts);

XLSX.utils.json_to_sheet takes an array of objects and returns a worksheet with automatically-generated "headers" based on the keys of the objects. 获取一个对象数组,并返回一个工作表,其中包含基于对象键自动生成的“标题”。The default column order is determined by the first appearance of the field using Object.keys. 默认的列顺序由使用Object.keys的字段的首次出现来确定。The function accepts an options argument:函数接受一个选项参数:

Option Name选项名称Default默认值Description描述
headerUse specified field order (default Object.keys)使用指定的字段顺序(默认的Object.keys **
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认为n
skipHeaderfalseIf true, do not include header row in output如果为true,则不在输出中包括标题行
nullErrorfalseIf true, emit #NULL! error cells for null values如果为true,则针对null值发出#NULL!错误单元格
UTCfalseIf true, dates are interpreted using UTC methods如果为true,则使用UTC方法解释日期 **
densefalseEmit dense sheet object

UTC option is explained in "Dates"UTC选项在“日期”中有说明

All fields from each row will be written!将写入每行中的所有字段! header hints at a particular order but is not exclusive. 暗示了特定的顺序,但不是排他性的。To remove fields from the export, filter the data source.若要从导出中删除字段,请筛选数据源。

Some data sources have special options to filter properties. 某些数据源具有用于筛选属性的特殊选项。For example, MongoDB will add the _id field when finding data from a collection:例如,MongoDB在从集合中查找数据时会添加_id字段:

const aoo_with_id = await coll.find({}).toArray();
const ws = XLSX.utils.json_to_sheet(aoo_with_id); // includes _id column

This can be filtered out through the projection property:这可以通过projection属性筛选掉:

const aoo = await coll.find({}, {projection:{_id:0}}).toArray(); // no _id !
const ws = XLSX.utils.json_to_sheet(aoo);

If a data source does not provide a filter option, it can be filtered manually:如果数据源不提供筛选选项,则可以手动进行筛选:

const aoo = data.map(obj => Object.fromEntries(Object.entries(obj).filter(r => headers.indexOf(r[0]) > -1)));
  • If header is an array, missing keys will be added in order of first use.如果header是一个数组,则将按首次使用的顺序添加缺少的键。
  • Cell types are deduced from the type of each value. 单元类型是根据每个值的类型推导出来的。For example, a Date object will generate a Date cell, while a string will generate a Text cell.例如,Date对象将生成Date单元格,而字符串将生成Text单元格。
  • Null values will be skipped by default. 默认情况下将跳过空值。If nullError is true, an error cell corresponding to #NULL! will be written to the worksheet.如果nullErrortrue,则对应于#NULL!的错误单元格将写入工作表。
Result
Loading...
Live Editor

The example sheet cannot be reproduced using plain objects since JS object keys must be unique.由于JS对象键必须是唯一的,因此无法使用普通对象复制示例表

Typically the original data source will have different column names. 通常,原始数据源将具有不同的列名。After writing with json_to_sheet, the aoa_to_sheet method can rewrite the headers:使用json_to_sheet写入后,aoa_to_sheet方法可以重写头:

/* original array of objects原始对象数组 */
var data = [
{ S:1, h:2, t:5, J:6, S_1:7 },
{ S:2, h:3, t:6, J:7, S_1:8 },
{ S:3, h:4, t:7, J:8, S_1:9 },
{ S:4, h:5, e:6, e_1:7, t:8, J:9, S_1:0 },
];

/* column order for the generated worksheet生成的工作表的列顺序 */
// | A | B | C | D | E | F | G |
var data_headers = [ "S", "h", "e", "e_1", "t", "J", "S_1" ];

/* new headers for the first row of the worksheet工作表第一行的新标题 */
// | A | B | C | D | E | F | G |
var new_headers = [ "S", "h", "e", "e", "t", "J", "S" ];

/* write data with using data headers使用数据头写入数据 */
var ws = XLSX.utils.json_to_sheet(data, { header: data_headers });

/* replace first row替换第一行 */
XLSX.utils.sheet_add_aoa(worksheet, [new_headers], { origin: "A1" });

Add data from an array of objects to an existing worksheet将对象数组中的数据添加到现有工作表中

XLSX.utils.sheet_add_json(ws, aoo, opts);

XLSX.utils.sheet_add_json takes an array of objects and updates an existing worksheet object. 获取一个对象数组并更新现有的工作表对象。It follows the same process as json_to_sheet and accepts an options argument:它遵循与json_to_sheet相同的过程,并接受一个options参数:

Option Name选项名称Default默认值Description描述
headerUse specified column order (default Object.keys)使用指定的列顺序(默认的Object.keys
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认为n
skipHeaderfalseIf true, do not include header row in output如果为true,则不在输出中包括标题行
nullErrorfalseIf true, emit #NULL! error cells for null values如果为true,则针对null值发出#NULL!错误单元格
originUse specified cell as starting point (see below)使用指定的单元格作为起点(见下文)
UTCfalseIf true, dates are interpreted using UTC methods如果为true,则使用UTC方法解释日期 **

UTC option is explained in "Dates"UTC选项在“日期”中有说明

origin is expected to be one of:预计是以下其中之一:

originDescription描述
(cell object)Use specified cell (cell object)使用指定的单元格(单元格对象)
(string)Use specified cell (A1-Style cell)使用指定的单元格(A1样式单元格)
(number >= 0)Start from the first column at specified row (0-indexed)从指定行的第一列开始(0索引)
-1Append to bottom of worksheet starting on first column从第一列开始追加到工作表底部
(default)Start from cell A1从单元格A1开始

This example worksheet can be built up in the order A1:G1, A2:B4, E2:G4, A5:G5:此示例工作表可以按A1:G1, A2:B4, E2:G4, A5:G5的顺序生成:

/* Start from an empty worksheet从空工作表开始 */
var ws = XLSX.utils.aoa_to_sheet([[]]);

/* Header order */
var header = ["A", "B", "C", "D", "E", "F", "G"];

/* First row第一行 */
XLSX.utils.sheet_add_json(ws, [
{ A: "S", B: "h", C: "e", D: "e", E: "t", F: "J", G: "S" }
], {header: header, skipHeader: true});

/* Write data starting at A2 */
XLSX.utils.sheet_add_json(ws, [
{ A: 1, B: 2 }, { A: 2, B: 3 }, { A: 3, B: 4 }
], {header: header, skipHeader: true, origin: "A2"});

/* Write data starting at E2 */
XLSX.utils.sheet_add_json(ws, [
{ A: 5, B: 6, C: 7 }, { A: 6, B: 7, C: 8 }, { A: 7, B: 8, C: 9 }
], {header: ["A", "B", "C"], skipHeader: true, origin: { r: 1, c: 4 }});

/* Append row追加行 */
XLSX.utils.sheet_add_json(ws, [
{ A: 4, B: 5, C: 6, D: 7, E: 8, F: 9, G: 0 }
], {header: header, skipHeader: true, origin: -1});

If the header option is an array, sheet_add_json and sheet_to_json will append missing elements.如果header选项是一个数组,sheet_add_jsonsheet_to_json将附加缺失的元素。

This design enables consistent header order across calls:这种设计实现了调用之间一致的头顺序:

Result
Loading...
Live Editor

Array Output数组输出

var arr = XLSX.utils.sheet_to_json(ws, opts);

var aoa = XLSX.utils.sheet_to_json(ws, {header: 1, ...other_opts});

XLSX.utils.sheet_to_json generates an array of JS objects. The function takes an options argument:生成JS对象的数组。该函数采用一个选项参数:

Option Name选项名称Default默认值Description描述
rawtrueUse raw values (true) or formatted strings (false)使用原始值(true)或格式化字符串(false
range**Override Range (see table below)覆盖范围(见下表)
headerControl output format (see table below)控制输出格式(见下表)
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
defvalUse specified value in place of null or undefined使用指定的值代替nullundefined的值
blankrows**Include blank lines in the output在输出中包括空行 **
skipHiddenfalseDo not generate objects for hidden rows/columns不为隐藏的行/列生成对象
UTCfalseIf true, dates will be correct in UTC如果为true,则以UTC表示的日期将是正确的 **
  • raw only affects cells which have a format code (.z) field or a formatted text (.w) field.raw仅影响具有格式代码(.z)字段或格式化文本(.w)字段的单元格。
  • If header is specified, the first row is considered a data row; if header is not specified, the first row is the header row and not considered data.如果指定了header,则第一行被视为数据行;如果未指定header,则第一行为头行,不视为数据。
  • When header is not specified, the conversion will automatically disambiguate header entries by affixing _ and a count starting at 1. 如果未指定header,则转换将通过附加_和从1开始的计数来自动消除头部条目的歧义。For example, if three columns have header foo the output fields are foo, foo_1, foo_2例如,如果三列的标题为foo,则输出字段为foofoo_1foo_2
  • null values are returned when raw is true but are skipped when false.rawtrue时返回null值,但当为false时跳过null值。
  • If defval is not specified, null and undefined values are skipped normally. 如果未指定defval,则通常会跳过null和未定义的值。If specified, all null and undefined points will be filled with defval如果指定,所有空点和未定义点都将填充defval
  • When header is 1, the default is to generate blank rows. header1时,默认情况是生成空行。blankrows must be set to false to skip blank rows.必须设置为false才能跳过空白行。
  • When header is not 1, the default is to skip blank rows. header不为1时,默认情况是跳过空白行。blankrows must be true to generate blank rows必须为true才能生成空行
  • UTC option is explained in "Dates"UTC选项在“日期”中有说明

range is expected to be one of:预计是以下其中之一:

rangeDescription描述
(number)Use worksheet range but set starting row to the value使用工作表区域,但将起始行设置为值
(string)Use specified range (A1-Style bounded range string)使用指定的范围(A1样式有界范围字符串)
(default)Use worksheet range (ws['!ref'])使用工作表区域(ws['!ref']

header is expected to be one of:预计是以下其中之一:

headerDescription描述
1Generate an array of arrays生成数组的数组
"A"Row object keys are literal column labels行对象键是文字列标签
array of stringsUse specified strings as keys in row objects使用指定的字符串作为行对象中的键
(default)Read and disambiguate first row as keys将第一行作为关键字读取并消除歧义
  • If header is not 1, the row object will contain the non-enumerable property __rowNum__ that represents the row of the sheet corresponding to the entry.如果header不为1,则行对象将包含不可枚举的属性__rowNum__,该属性表示与条目对应的工作表的行。
  • If header is an array, the keys will not be disambiguated. This can lead to unexpected results if the array values are not unique!如果头是一个数组,键将不会被消除歧义。如果数组值不是唯一的,这可能会导致意外的结果!

For the example worksheet:对于示例工作表:

Result
Loading...
Live Editor