简体   繁体   English

使用客户端 JavaScript 创建一个带有几种样式的 excel 文件(如果可能,使用 js-xlsx 库)

[英]Create an excel file with a few styles using client side JavaScript (if possible using js-xlsx library)

I want to create an excel file(in .xlsx format) and make it available for download using Client Side JavaScript .我想创建一个 excel 文件( .xlsx格式)并使用Client Side JavaScript使其可供下载。 I was able to create a sample file using js-xlsx library.我能够使用js-xlsx库创建一个示例文件。 But I am not able to apply any styles to it.但我无法对其应用任何样式。 At least some basic styles including background color to header, bold font for header and text wrapping for the cells are required.至少需要一些基本样式,包括标题的背景颜色、标题的粗体和单元格的文本换行

js-xlsx library documentation says that we can give styles using Cell Object . js-xlsx库文档说我们可以使用Cell Object提供样式。

I tried giving styles using the cell object but it is not reflecting in the downloaded .xlsx file.我尝试使用单元格对象提供样式,但它没有反映在下载的 .xlsx 文件中。 I even tried reading a .xlsx file and writing the same file back using XLSX.write() function.我什至尝试读取 .xlsx 文件并使用XLSX.write()函数写回相同的文件。 But it gives back an excel file with no styles at all.但它返回一个完全没有样式的 excel 文件。 Ideally I expect the downloaded file to have the same styles of uploaded file.理想情况下,我希望下载的文件具有与上传文件相同的样式。 No font color or background colors were applied in the recreated file.在重新创建的文件中没有应用字体颜色或背景颜色。 I use Excel 2013 for testing the downloaded files.我使用Excel 2013来测试下载的文件。

Please find below the excel screenshots before and after uploading.请在下面找到上传前后的excel截图。

Original File原始文件

在此处输入图片说明

Downloaded File下载的文件

在此处输入图片说明

The code is given below.代码如下。

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<script type="text/javascript" src="xlsx.core.min.js"></script>
<script type="text/javascript" src="Blob.js"></script>
<script type="text/javascript" src="FileSaver.js"></script>

<script>

function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}   

/* set up XMLHttpRequest */
var url = "template-sample.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";

oReq.onload = function(e) {
  var arraybuffer = oReq.response;

  /* convert data to binary string */
  var data = new Uint8Array(arraybuffer);
  var arr = new Array();
  for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
  var bstr = arr.join("");

  /* Call XLSX */
  var workbook = XLSX.read(bstr, {type:"binary", cellStyles:true});

    console.log("read workbook");
    console.log(workbook);
  /* DO SOMETHING WITH workbook HERE */
    var wbout = XLSX.write(workbook, {bookType:'xlsx', bookSST:true, type: 'binary', cellStyles: true});
    saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), "template-download.xlsx");

}

function read(){
    oReq.send();    
}


</script>


</head>
<body>
    <button onclick="read()">save xlsx</button>
</body></html>

Sample code was taken from here .示例代码取自此处

What I look forward is either an option to give styles to cells using js-xlsx library or another library which provides this functionality.我期待的是使用js-xlsx库或提供此功能的另一个库为单元格提供样式的选项。 I found a library named exceljs , but it requires node js to support it.我找到了一个名为exceljs的库,但是它需要node js来支持它。 I am looking for a purely client side based solution.我正在寻找一个纯粹基于客户端的解决方案。 This is to be used for a Cordova based tablet and desktop application.这将用于基于Cordova的平板电脑和桌面应用程序。

After some research I was able to find the solution to my own question.经过一些研究,我能够找到我自己问题的解决方案。 I found a new library named xlsx-style for giving styles.我发现了一个名为xlsx-style的新库,用于提供样式。 xlsx-style is build on top of js-xlsx for giving styles also to the generated excel file. xlsx-style建立在js-xlsx之上,用于为生成的 excel 文件提供样式。 The styles can be given to the cells using a new attribute inside cell object.可以使用单元格对象内的新属性将样式赋予单元格。

The explanation is available at the npm xlsx-style page.解释可在 npm xlsx-style页面上找到。

Styling is given using a style object associated with each cell.样式是使用与每个单元格关联的样式对象给出的。 Font, Color, alignment etc can be given using this style object.可以使用此样式对象给出字体、颜色、对齐方式等。

I have added a minimalist demo in a github page .我在github 页面中添加了一个极简的演示。 The sample code is available at this github repository .示例代码可在此github 存储库中获得

You can find the screenshot of the generated excel page below.您可以在下面找到生成的 excel 页面的屏幕截图。 在此处输入图片说明

There are only a couple of examples for using xlsx-style which I didn't really find clear or all that helpful to get what I needed fast.只有几个使用xlsx 样式的示例,我并没有真正找到清楚或所有有助于快速获得所需内容的示例。

Here is my solution using xlsx-style with the barebones needed to create a workbook, set a cell value, and color that cell.这是我使用 xlsx 样式的解决方案,其中包含创建工作簿、设置单元格值和为该单元格着色所需的准系统。

I struggled a little bit with getting the right xlsx.core.min.js file, for some reason not all versions have this included.我在获得正确的 xlsx.core.min.js 文件方面遇到了一些困难,由于某种原因,并非所有版本都包含此文件。 I ended up copying directly from Nithin Baby (the anwsers demo)我最终直接从 Nithin Baby(anwsers 演示)复制

Heres the simple version of the code这是代码的简单版本

/* Object for the excel workbook data */
class Workbook {
    constructor() {
        this.SheetNames = [];
        this.Sheets = {};
    }
}

/* function for downloading the excel file */
function s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
}

// create the worksheet data
var ws_data = {}
var range = { s: { c: 0, r: 0 }, e: { c: 10, r: 10 } }; // worksheet cell range 
ws_data['!ref'] = XLSX.utils.encode_range(range); // set cell the range

var cell = { // create cell
    v: 'test', // value
    s: { // style
        fill: {
            fgColor: { rgb: "FF6666" } // red
        }
    }
}
ws_data[XLSX.utils.encode_cell({ c: 1, r: 1 })] = cell; // add the cell to the sheet data

// create workbook and download
var wb = new Workbook();
wb.SheetNames.push('test'); // create new worksheet
wb.Sheets['test'] = ws_data; // set workseet data to the cell data
var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'binary' }); //workbook output
saveAs(new Blob([s2ab(wbout)], { type: "application/octet-stream" }), "Test Color.xlsx") // save workbook

Couple things to note.需要注意的几件事。

XLSX.utils.encode_cell({ c: 1, r: 1 }) is their way of assigning excel cords to numbers. XLSX.utils.encode_cell({ c: 1, r: 1 })是他们将 excel 线分配给数字的方式。 for example: { c: 1, r: 1 } == 'B2'例如: { c: 1, r: 1 } == 'B2'

If you can get the excel file to download but the cell data doesn't show up it most likely has to do with the sheets range value.如果您可以下载 excel 文件但未显示单元格数据,则很可能与工作表范围值有关。 Make sure it matches or is bigger than the amount of data.确保它匹配或大于数据量。 range = { s: { c: 0, r: 0 }, e: { c: 10, r: 10 } }; where 's' = current and 'e' = total from what i've gathered.其中“s”=当前,“e”=我收集到的总数。

xlsx-style has more attributes that can be set when creating the cell its worth a quick skim to know what's there. xlsx-style有更多的属性可以在创建单元格时设置,值得快速浏览一下以了解其中的内容。 Now its up to you to figure out how you want to create/style the cells you need for your output and set to the range value appropriately.现在由您决定如何创建/设置输出所需的单元格并适当设置范围值。

Using xlsx-style , foreach yout collection 'WorkSheet' and add the style before add in 'WorkBook'.使用xlsx-style ,为每个集合“WorkSheet”添加样式,然后再添加到“WorkBook”中。 The property responsible for this process is the 's' (style).负责此过程的属性是“s”(样式)。

Sample:样品:

_.forEach(ws, (v, c) => {
    if (c !== '!ref') {
        if (header.indexOf(v.v) >= 0) {
            ws[c]['s'] = {
                fill: {
                patternType: 'solid', // none / solid
                fgColor: {rgb: 'FFD3D3D3'}
                }
            }
        }
    }
})

As another alternative for writing simple *.xlsx files I'd propose write-excel-file package.作为编写简单*.xlsx文件的另一种替代方法,我建议使用write-excel-file包。

https://npmjs.com/package/write-excel-file https://npmjs.com/package/write-excel-file

It supports styling cells with bold font, text color, background color, horizontal alignment, vertical alignment and text wrapping on overflow.它支持带有粗体、文本颜色、背景颜色、水平对齐、垂直对齐和文本环绕的样式单元格。

import writeXlsxFile from 'write-excel-file'

const data = [
  [{
    value: 'Row 1, Col 1',
    fontWeight: 'bold'
  }, {
    value: 'Row 1, Col 2',
    color: '#ffffff',
    backgroundColor: '#cc0000'
  }],
  [{
    value: 'Row 2, Col 1',
    align: 'right',
    alignVertical: 'top'
  }, {
    value: 'Row 2, Col 2. Long Text \n Multi-line',
    wrap: true
  }]
]

await writeXlsxFile(data, {
  fileName: 'file.xlsx'
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM