Skip to main content

Utility Functions实用工具函数

The sheet_to_* functions accept a worksheet and an optional options object.sheet_to_*函数接受工作表和可选选项对象。

The *_to_sheet functions accept a data object and an optional options object.*_to_sheet函数接受数据对象和可选选项对象。

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

XXX| A | B | C | D | E | F | G |
---+---+---+---+---+---+---+---+
1 | S | h | e | e | t | J | S |
2 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
3 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |

Array of Arrays Input数组输入数组

XLSX.utils.aoa_to_sheet takes an array of arrays of JS values and returns a worksheet resembling the input data. 获取JS值数组并返回类似于输入数据的工作表。 Numbers, Booleans and Strings are stored as the corresponding styles. 数字、布尔值和字符串存储为相应的样式。 Dates are stored as date or numbers. 日期存储为日期或数字。Array holes and explicit undefined values are skipped. 跳过数组孔和显式undefined值。null values may be stubbed. 空值可以存根。All other values are stored as strings. 所有其他值都存储为字符串。 The function takes an options argument:该函数采用options参数:

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!错误单元格
Examples示例 (click to show)

To generate the example sheet:要生成示例工作表:

var ws = XLSX.utils.aoa_to_sheet([
"SheetJS".split(""),
[1,2,3,4,5,6,7],
[2,3,4,5,6,7,8]
]);

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相同的过程,并接受options参数:

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)使用指定的单元格作为起点(见下文)

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开始
Examples示例 (click to show)

Consider the worksheet:考虑工作表:

XXX| A | B | C | D | E | F | G |
---+---+---+---+---+---+---+---+
1 | S | h | e | e | t | J | S |
2 | 1 | 2 | | | 5 | 6 | 7 |
3 | 2 | 3 | | | 6 | 7 | 8 |
4 | 3 | 4 | | | 7 | 8 | 9 |
5 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |

This worksheet can be built up in the order A1:G1, A2:B4, E2:G4, A5:G5:该工作表可以按A1:G1, A2:B4, E2:G4, A5:G5的顺序建立:

/* Initial row */
var ws = XLSX.utils.aoa_to_sheet([ "SheetJS".split("") ]);

/* Write data starting at A2 */
XLSX.utils.sheet_add_aoa(ws, [[1,2], [2,3], [3,4]], {origin: "A2"});

/* Write data starting at 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});

Array of Objects Input对象数组输入

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:该函数接受options参数:

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!错误单元格
  • All fields from each row will be written. 将写入每行的所有字段。If header is an array and it does not contain a particular field, the key will be appended to the array.如果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对象将生成日期单元格,而字符串将生成文本单元格。
  • 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!将写入工作表。
Examples示例 (click to show)

The original sheet cannot be reproduced using plain objects since JS object keys must be unique. 由于JS对象键必须是唯一的,因此无法使用普通对象复制原始图纸。After replacing the second e and S with e_1 and S_1:将第二个eS替换为e_1s_1后:

var ws = XLSX.utils.json_to_sheet([
{ S:1, h:2, e:3, e_1:4, t:5, J:6, S_1:7 },
{ S:2, h:3, e:4, e_1:5, t:6, J:7, S_1:8 }
], {header:["S","h","e","e_1","t","J","S_1"]});

Alternatively, the header row can be skipped:或者,可以跳过标题行:

var ws = XLSX.utils.json_to_sheet([
{ A:"S", B:"h", C:"e", D:"e", E:"t", F:"J", G:"S" },
{ A: 1, B: 2, C: 3, D: 4, E: 5, F: 6, G: 7 },
{ A: 2, B: 3, C: 4, D: 5, E: 6, F: 7, G: 8 }
], {header:["A","B","C","D","E","F","G"], skipHeader:true});

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!空值的错误单元格
originUse specified cell as starting point (see below)使用指定的单元格作为起点(见下文)

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开始
Examples示例 (click to show)

Consider the worksheet:考虑工作表:

XXX| A | B | C | D | E | F | G |
---+---+---+---+---+---+---+---+
1 | S | h | e | e | t | J | S |
2 | 1 | 2 | | | 5 | 6 | 7 |
3 | 2 | 3 | | | 6 | 7 | 8 |
4 | 3 | 4 | | | 7 | 8 | 9 |
5 | 4 | 5 | 6 | 7 | 8 | 9 | 0 |

This worksheet can be built up in the order A1:G1, A2:B4, E2:G4, A5:G5:该工作表可以按A1:G1, A2:B4, E2:G4, A5:G5的顺序建立:

/* Initial row */
var ws = XLSX.utils.json_to_sheet([
{ A: "S", B: "h", C: "e", D: "e", E: "t", F: "J", G: "S" }
], {header: ["A", "B", "C", "D", "E", "F", "G"], 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 }
], {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 }
], {skipHeader: true, origin: { r: 1, c: 4 }, header: [ "A", "B", "C" ]});

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

HTML Table Input

XLSX.utils.table_to_sheet takes a table DOM element and returns a worksheet resembling the input table. 获取一个表DOM元素并返回一个类似于输入表的工作表。Numbers are parsed. 数字被解析。All other data will be stored as strings.所有其他数据将存储为字符串。

XLSX.utils.table_to_book produces a minimal workbook based on the worksheet.基于工作表生成最小工作簿。

Both functions accept options arguments:两个函数都接受选项参数:

Option Name选项名称Default默认值Description描述
rawIf true, every cell will hold raw strings如果为true,则每个单元格都将包含原始字符串
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认值为n
sheetRows0If >0, read the first sheetRows rows of the table如果>0,则读取表的第一个sheetRows
displayfalseIf true, hidden rows and cells will not be parsed如果为true,则不会分析隐藏的行和单元格
Examples示例 (click to show)

To generate the example sheet, start with the HTML table:要生成示例工作表,请从HTML表开始:

<table id="sheetjs">
<tr><td>S</td><td>h</td><td>e</td><td>e</td><td>t</td><td>J</td><td>S</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td></tr>
<tr><td>2</td><td>3</td><td>4</td><td>5</td><td>6</td><td>7</td><td>8</td></tr>
</table>

To process the table:处理表格:

var tbl = document.getElementById('sheetjs');
var wb = XLSX.utils.table_to_book(tbl);

Note: XLSX.read can handle HTML represented as strings.注意:XLSX.read可以处理以字符串表示的HTML。

XLSX.utils.sheet_add_dom takes a table DOM element and updates an existing worksheet object. 获取表DOM元素并更新现有工作表对象。It follows the same process as table_to_sheet and accepts an options argument:它遵循与table_to_sheet相同的过程,并接受options参数:

Option Name选项名称Default默认值Description描述
rawIf true, every cell will hold raw strings如果为true,则每个单元格都将包含原始字符串
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
cellDatesfalseStore dates as type d (default is n)将日期存储为类型d(默认值为n
sheetRows0If >0, read the first sheetRows rows of the table如果>0,则读取表的第一个sheetRows
displayfalseIf true, hidden rows and cells will not be parsed如果为true,则不会分析隐藏的行和单元格

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开始
Examples示例 (click to show)

A small helper function can create gap rows between tables:小助手函数可以在表之间创建间隙行:

function create_gap_rows(ws, nrows) {
var ref = XLSX.utils.decode_range(ws["!ref"]); // get original range
ref.e.r += nrows; // add to ending row
ws["!ref"] = XLSX.utils.encode_range(ref); // reassign row
}

/* first table */
var ws = XLSX.utils.table_to_sheet(document.getElementById('table1'));
create_gap_rows(ws, 1); // one row gap after first table

/* second table */
XLSX.utils.sheet_add_dom(ws, document.getElementById('table2'), {origin: -1});
create_gap_rows(ws, 3); // three rows gap after second table

/* third table */
XLSX.utils.sheet_add_dom(ws, document.getElementById('table3'), {origin: -1});

Formulae Output公式输出

XLSX.utils.sheet_to_formulae generates an array of commands that represent how a person would enter data into an application. 生成一组命令,表示用户将如何将数据输入应用程序。 Each entry is of the form A1-cell-address=formula-or-value. 每个条目的格式为A1-cell-address=formula-or-valueString literals are prefixed with a ' in accordance with Excel.根据Excel,字符串文字的前缀为'

Examples示例 (click to show)

For the example sheet:对于示例页:

> var o = XLSX.utils.sheet_to_formulae(ws);
> [o[0], o[5], o[10], o[15], o[20]];
[ 'A1=\'S', 'F1=\'J', 'D2=4', 'B3=3', 'G3=8' ]

Delimiter-Separated Output分隔符分隔的输出

As an alternative to the writeFile CSV type, XLSX.utils.sheet_to_csv also produces CSV output. 作为writeFile CSV类型的替代,XLSX.utils.sheet_to_csv也会生成CSV输出。The function takes an options argument:该函数采用options参数:

Option Name选项名称Default默认值Description描述
FS",""Field Separator" delimiter between fields字段之间的“字段分隔符”分隔符
RS"\n""Record Separator" delimiter between rows行之间的“记录分隔符”分隔符
dateNFFMT 14Use specified date format in string output在字符串输出中使用指定的日期格式
stripfalseRemove trailing field separators in each record删除每个记录中的尾部字段分隔符 **
blankrowstrueInclude blank lines in the CSV output在CSV输出中包括空行
skipHiddenfalseSkips hidden rows/columns in the CSV output跳过CSV输出中隐藏的行/列
forceQuotesfalseForce quotes around fields在字段周围强制引用
  • strip will remove trailing commas from each line under default FS/RS将删除默认FS/RS下每行的尾随逗号
  • blankrows must be set to false to skip blank lines.必须设置为false才能跳过空行。
  • Fields containing the record or field separator will automatically be wrapped in double quotes; forceQuotes forces all cells to be wrapped in quotes.包含记录或字段分隔符的字段将自动用双引号括起来;forceQuotes强制所有单元格都用引号括起来。
  • XLSX.write with csv type will always prepend the UTF-8 byte-order mark for Excel compatibility. 带有csv类型的XLSX.write将始终在UTF-8字节顺序标记之前,以实现Excel兼容性。sheet_to_csv returns a JS string and omits the mark. 返回JS字符串并忽略标记。Using XLSX.write with type string will also skip the mark.XLSX.write与类型string一起使用也会跳过标记。
Examples示例 (click to show)

For the example sheet:对于示例页:

> console.log(XLSX.utils.sheet_to_csv(ws));
S,h,e,e,t,J,S
1,2,3,4,5,6,7
2,3,4,5,6,7,8
> console.log(XLSX.utils.sheet_to_csv(ws, {FS:"\t"}));
S h e e t J S
1 2 3 4 5 6 7
2 3 4 5 6 7 8
> console.log(XLSX.utils.sheet_to_csv(ws,{FS:":",RS:"|"}));
S:h:e:e:t:J:S|1:2:3:4:5:6:7|2:3:4:5:6:7:8|

UTF-16 Unicode TextUTF-16 Unicode文本

The txt output type uses the tab character as the field separator. txt输出类型使用制表符作为字段分隔符。If the codepage library is available (included in full distribution but not core), the output will be encoded in CP1200 and the BOM will be prepended.如果codepage库可用(包括在完整发行版中,但不包括核心版),则输出将在CP1200中编码,BOM将被前置。

XLSX.utils.sheet_to_txt takes the same arguments as sheet_to_csv.采用与sheet_to_csv相同的参数。

HTML Output

As an alternative to the writeFile HTML type, XLSX.utils.sheet_to_html also produces HTML output. 作为writeFile HTML类型的替代方法,XLSX.utils.sheet_to_html也会生成HTML输出。The function takes an options argument:该函数采用options参数:

Option Name选项名称Default默认值Description描述
idSpecify the id attribute for the TABLE element指定TABLE元素的id属性
editablefalseIf true, set contenteditable="true" for every TD如果为true,则为每个TD设置contenteditable="true"
headerOverride header (default html body)覆盖标题(默认html body
footerOverride footer (default /body /html)覆盖页脚(默认/body /html
Examples示例 (click to show)

For the example sheet:对于示例页:

> console.log(XLSX.utils.sheet_to_html(ws));
// ...

JSON

XLSX.utils.sheet_to_json generates different types of JS objects. 生成不同类型的JS对象。The function takes an options argument:该函数采用options参数:

Option Name选项名称Default默认值Description描述
rawtrueUse raw values (true) or formatted strings (false)使用原始值(true)或格式化字符串(false
rangefrom WSOverride 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使用指定值代替null或未定义值
blankrows**Include blank lines in the output在输出中包括空行 **
  • raw only affects cells which have a format code (.z) field or a formatted text (.w) field.仅影响具有格式代码(.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时跳过。
  • 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. header为1时,默认为生成空行。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才能生成空行

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 ("2D Array")生成数组(“2D数组”)
"A"Row object keys are literal column labels行对象键是文字列标签
array of strings字符串数组Use 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,则row对象将包含不可枚举属性__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!如果数组值不唯一,则可能导致意外结果!
Examples示例 (click to show)

For the example sheet:对于示例页:

> XLSX.utils.sheet_to_json(ws);
[ { S: 1, h: 2, e: 3, e_1: 4, t: 5, J: 6, S_1: 7 },
{ S: 2, h: 3, e: 4, e_1: 5, t: 6, J: 7, S_1: 8 } ]

> XLSX.utils.sheet_to_json(ws, {header:"A"});
[ { A: 'S', B: 'h', C: 'e', D: 'e', E: 't', F: 'J', G: 'S' },
{ A: '1', B: '2', C: '3', D: '4', E: '5', F: '6', G: '7' },
{ A: '2', B: '3', C: '4', D: '5', E: '6', F: '7', G: '8' } ]

> XLSX.utils.sheet_to_json(ws, {header:["A","E","I","O","U","6","9"]});
[ { '6': 'J', '9': 'S', A: 'S', E: 'h', I: 'e', O: 'e', U: 't' },
{ '6': '6', '9': '7', A: '1', E: '2', I: '3', O: '4', U: '5' },
{ '6': '7', '9': '8', A: '2', E: '3', I: '4', O: '5', U: '6' } ]

> XLSX.utils.sheet_to_json(ws, {header:1});
[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
[ '1', '2', '3', '4', '5', '6', '7' ],
[ '2', '3', '4', '5', '6', '7', '8' ] ]

Example showing the effect of raw:显示raw效果的示例:

> ws['A2'].w = "3";                          // set A2 formatted string value

> XLSX.utils.sheet_to_json(ws, {header:1, raw:false});
[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
[ '3', '2', '3', '4', '5', '6', '7' ], // <-- A2 uses the formatted string
[ '2', '3', '4', '5', '6', '7', '8' ] ]

> XLSX.utils.sheet_to_json(ws, {header:1});
[ [ 'S', 'h', 'e', 'e', 't', 'J', 'S' ],
[ 1, 2, 3, 4, 5, 6, 7 ], // <-- A2 uses the raw value
[ 2, 3, 4, 5, 6, 7, 8 ] ]