杨更生 發表於 2022-1-26 11:46:00

从服务端生成Excel电子表格(Node.js+SpreadJS)

<p>Node.js是一个基于Chrome V8引擎的JavaScript运行环境,通常用于创建网络应用程序。它可以同时处理多个连接,并且不像其他大多数模型那样依赖线程。</p>
<p>对于 Web 开发者来说,从数据库或Web服务器获取数据,然后输出到Excel文件以进行进一步分析的场景时有发生。我们的技术团队在跟国内外各行各业用户交流的过程中,就曾发现有很多的用户尝试在Node.js的环境下运行SpreadJS 纯前端表格控件,借助该控件,可以在服务器不预装任何Excel依赖项的情况下,收集用户输入的信息,并将其自动导出到Excel文件中。</p>
<p>为了满足广大技术爱好者的需要,同时减少大家在未来技术选型方面所走的弯路,本文将就SpreadJS 与 Node.js之间的技术性方案进行探讨!</p>
<h3 id="一安装-spreadjs-和-node-js">一、安装 SpreadJS 和 Node .js</h3>
<p>首先,我们需要安装Node.js以及Mock-Browser,BufferJS和FileReader,大家可以前往以下链接进行下载,同步操作:</p>
<ul>
<li>Installing Node.js viaPackage Manager</li>
<li>Mock-Browser</li>
<li>BufferJS</li>
<li>FileReader</li>
</ul>
<p>我们将使用Visual Studio创建应用程序。打开Visual Studio后,使用JavaScript&amp;gt; Node.js&amp;gt;Blank Node.js控制台应用程序模板创建一个新应用程序。这将自动创建所需的文件并打开" app.js"文件,也是我们将要更改的唯一文件。</p>
<p>对于BufferJS库,您需要下载该软件包,然后通过导航到项目文件夹(一旦创建)并运行以下命令,将其手动安装到项目中:</p>
<p>npm install</p>
<p>安装完成后,您可能需要打开项目的package.json文件并将其添加到" dependencies"部分。文件内容应如下所示:</p>
<pre><code>{
"name": "spread-sheets-node-jsapp",
"version": "0.0.0",
"description": "SpreadSheetsNodeJSApp",
"main": "app.js",
"author": {
   "name": "admin"
},
"dependencies": {
   "FileReader": "^0.10.2",
   "bufferjs": "1.0.0",
   "mock-browser": "^0.92.14"
}
}

</code></pre>
<p>在此示例中,我们将使用Node.js的文件系统模块。我们可以将其加载到:</p>
<pre><code>var fs = require('fs')
</code></pre>
<p>为了将SpreadJS与Node.js结合使用,我们还需要加载已安装的Mock-Browser:</p>
<pre><code>var mockBrowser =require('mock-browser').mocks.MockBrowser
</code></pre>
<p>在加载SpreadJS脚本之前,我们需要初始化模拟浏览器。初始化我们稍后在应用程序中可能需要使用的变量,尤其是" window"变量:</p>
<pre><code>global.window =mockBrowser.createWindow()
global.document = window.document
global.navigator = window.navigator
global.HTMLCollection =window.HTMLCollection
global.getComputedStyle =window.getComputedStyle

</code></pre>
<p>初始化FileReader库:</p>
<pre><code>var fileReader = require('filereader');
global.FileReader = fileReader;

</code></pre>
<h3 id="二使用spreadjs-npm-包">二、使用SpreadJS npm 包</h3>
<p>将SpreadJS安装文件中的SpreadJS Sheets和ExcelIO包添加到项目中。</p>
<p>您可以通过右键单击解决方案资源管理器的" npm"部分并将它们添加到您的项目中,然后选择"安装新的NPM软件包"。您应该能够搜索" GrapeCity"并安装以下2个软件包:</p>
<pre><code>@grapecity/spread-sheets
@grapectiy/spread-excelio

</code></pre>
<p>将SpreadJS npm软件包添加到项目后,正确的依赖关系将被写入package.json:</p>
<pre><code>1.        {
2.        "name": "spread-sheets-node-jsapp",
3.        "version": "0.0.0",
4.        "description": "SpreadSheetsNodeJSApp",
5.        "main": "app.js",
6.        "author": {
7.           "name": "admin"
8.        },
9.          "dependencies":{
10.           "@grapecity/spread-excelio": "^11.2.1",
11.           "@grapecity/spread-sheets": "^11.2.1",
12.           "FileReader": "^0.10.2",
13.           "bufferjs": "1.0.0",
14.           "mock-browser": "^0.92.14"
15.          }
16.        }

</code></pre>
<p>现在我们需要在app.js文件中引入它:</p>
<pre><code>var GC =require('@grapecity/spread-sheets')
var GCExcel =require('@grapecity/spread-excelio');

</code></pre>
<p>使用npm软件包时,还需要设置许可证密钥(点击此处,免费申请许可证密钥):</p>
<pre><code>GC.Spread.Sheets.LicenseKey ="&lt;YOUR KEY HERE&gt;"
</code></pre>
<p>在这个特定的应用程序中,我们将向用户显示他们正在使用哪个版本的SpreadJS。为此,我们可以引入package.json文件,然后引用依赖项以获取版本号:</p>
<pre><code>var packageJson =require('./package.json')
console.log('\n** Using Spreadjs Version"' + packageJson.dependencies["@grapecity/spread-sheets"] +'" **')

</code></pre>
<h3 id="三将-excel-文件加载到您的-nodejs-应用程序中">三、将 Excel 文件加载到您的 Node.js 应用程序中</h3>
<p>点击此处,下载现成的Excel模板文件,该文件包含了从用户那里获取数据。接下来,将数据放入文件中并导出。在这种情况下,文件是用户可以编辑的状态。</p>
<p>初始化工作簿和ExcelIO变量:</p>
<pre><code>var wb = new GC.Spread.Sheets.Workbook();
var excelIO = new GCExcel.IO();


</code></pre>
<p>我们在读取文件时将代码包装在try / catch块中。然后,初始化变量" readline",让您读取用户输入到控制台的数据。接下来,我们将其存储到一个JavaScript数组中,以便轻松填写Excel文件:</p>
<pre><code>// Instantiate the spreadsheet and modifyit
console.log('\nManipulatingSpreadsheet\n---');
try {
   var file = fs.readFileSync('./content/billingInvoiceTemplate.xlsx');
   excelIO.open(file.buffer, (data) =&gt; {
       wb.fromJSON(data);
       const readline = require('readline');
       var invoice = {
            generalInfo: [],
            invoiceItems: [],
            companyDetails: []
       };
   });
} catch (e) {
   console.error("** Error manipulating spreadsheet **");
   console.error(e);
}


</code></pre>
<h3 id="四收集用户输入信息">四、收集用户输入信息</h3>
<p><img src="https://img2022.cnblogs.com/blog/139239/202201/139239-20220126114114778-833506269.png" alt="" loading="lazy"></p>
<p>上图显示了我们正在使用的Excel文件。我们可以在excelio.open调用中创建一个单独的函数,以在控制台中提示用户需要的每一项内容。我们也可以创建一个单独的数组,将数据保存到每个输入后,然后将其推送到我们创建的invoice.generalInfo数组中:</p>
<pre><code>fillGeneralInformation();
function fillGeneralInformation() {
   console.log("-----------------------\nFill in InvoiceDetails\n-----------------------")
   const rl = readline.createInterface({
       input: process.stdin,
       output: process.stdout
   });
   var generalInfoArray = [];
   rl.question('Invoice Number: ', (answer) =&gt; {
       generalInfoArray.push(answer);
       rl.question('Invoice Date (dd Month Year): ', (answer) =&gt; {
         generalInfoArray.push(answer);
            rl.question('Payment Due Date (ddMonth Year): ', (answer) =&gt; {
                generalInfoArray.push(answer);
                rl.question('Customer Name: ',(answer) =&gt; {
                   generalInfoArray.push(answer);
                  rl.question('CustomerCompany Name: ', (answer) =&gt; {
                     generalInfoArray.push(answer);
                        rl.question('Customer Street Address:', (answer) =&gt; {
                           generalInfoArray.push(answer);
                           rl.question('Customer City, State, Zip (&lt;City&gt;, &lt;State Abbr&gt;&lt;Zip&gt;): ', (answer) =&gt; {
                              generalInfoArray.push(answer);
                               rl.question('Invoice Company Name: ', (answer) =&gt; {
                                 generalInfoArray.push(answer);
                                 rl.question('Invoice Street Address: ', (answer) =&gt; {
                                       generalInfoArray.push(answer);
                                       rl.question('Invoice City, State, Zip (&lt;City&gt;, &lt;State Abbr&gt;&lt;Zip&gt;): ', (answer) =&gt; {
                                          generalInfoArray.push(answer);
                                           rl.close();
                                           invoice.generalInfo.push({
                                             "invoiceNumber": generalInfoArray,
                                             "invoiceDate": generalInfoArray,
                                             "paymentDueDate": generalInfoArray,
                                             "customerName": generalInfoArray,
                                             "customerCompanyName": generalInfoArray,
                                             "customerStreetAddress": generalInfoArray,
                                             "customerCityStateZip": generalInfoArray,
                                             "invoiceCompanyName": generalInfoArray,
                                             "invoiceStreetAddress": generalInfoArray,
                                             "invoiceCityStateZip": generalInfoArray,
                                          });
                                           console.log("General Invoice Information Stored");
                                           fillCompanyDetails();
                                        });
                                    });
                               });
                            });
                        });
                  });
                });
            });
       });
   });
}


</code></pre>
<p>该函数被称为" fillCompanyDetails",目的是收集有关公司的信息以填充到工作簿的第二张表中:</p>
<pre><code>function fillCompanyDetails() {
   console.log("-----------------------\nFill in CompanyDetails\n-----------------------")
   const rl = readline.createInterface({
       input: process.stdin,
       output: process.stdout
   });
   var companyDetailsArray = []
   rl.question('Your Name: ', (answer) =&gt; {
       companyDetailsArray.push(answer);
       rl.question('Company Name: ', (answer) =&gt; {
            companyDetailsArray.push(answer);
            rl.question('Address Line 1: ',(answer) =&gt; {
               companyDetailsArray.push(answer);
                rl.question('Address Line 2: ',(answer) =&gt; {
                   companyDetailsArray.push(answer);
                  rl.question('Address Line3: ', (answer) =&gt; {
                     companyDetailsArray.push(answer);
                        rl.question('AddressLine 4: ', (answer) =&gt; {
                           companyDetailsArray.push(answer);
                           rl.question('Address Line 5: ', (answer) =&gt; {
                               companyDetailsArray.push(answer);
                               rl.question('Phone: ', (answer) =&gt; {
                                 companyDetailsArray.push(answer);
                                 rl.question('Facsimile: ', (answer) =&gt; {
                                       companyDetailsArray.push(answer);
                                        rl.question('Website: ', (answer)=&gt; {
                                           companyDetailsArray.push(answer);
                                           rl.question('Email: ', (answer) =&gt; {
                                                companyDetailsArray.push(answer);
                                             rl.question('Currency Abbreviation: ', (answer) =&gt; {
                                                   companyDetailsArray.push(answer);
                                                    rl.question('Beneficiary: ',(answer) =&gt; {
                                                       companyDetailsArray.push(answer);
                                                       rl.question('Bank: ', (answer) =&gt; {
                                                            companyDetailsArray.push(answer);
                                                         rl.question('Bank Address: ', (answer) =&gt; {
                                                               companyDetailsArray.push(answer);
                                                               rl.question('Account Number: ', (answer) =&gt; {
                                                                   companyDetailsArray.push(answer);
                                                                  rl.question('RoutingNumber: ', (answer) =&gt; {
                                                                     companyDetailsArray.push(answer);
                                                                     rl.question('Make Checks Payable To: ', (answer) =&gt; {
                                                                           companyDetailsArray.push(answer);
                                                                            rl.close();
                                                                           invoice.companyDetails.push({
                                                                               "yourName": companyDetailsArray,
                                                                               "companyName": companyDetailsArray,
                                                                               "addressLine1": companyDetailsArray,
                                                                               "addressLine2": companyDetailsArray,
                                                                               "addressLine3": companyDetailsArray,
                                                                               "addressLine4": companyDetailsArray,
                                                                               "addressLine5": companyDetailsArray,
                                                                              "phone":companyDetailsArray,
                                                                               "facsimile": companyDetailsArray,
                                                                              "website":companyDetailsArray,
                                                                               "email": companyDetailsArray,
                                                                               "currencyAbbreviation":companyDetailsArray,
                                                                               "beneficiary": companyDetailsArray,
                                                                               "bank":companyDetailsArray,
                                                                               "bankAddress": companyDetailsArray,
                                                                               "accountNumber": companyDetailsArray,
                                                                               "routingNumber": companyDetailsArray,
                                                                               "payableTo": companyDetailsArray
                                                                           });
                                                                           console.log("Invoice Company Information Stored");
                                                                            console.log("-----------------------\nFillin Invoice Items\n-----------------------")
                                                                           fillInvoiceItemsInformation();
                                                                        });
                                                                   });
                                                               });
                                                         });
                                                       });
                                                   });
                                             });
                                          });
                                        });
                                    });
                              });
                            });
                        });
                  });
                });
            });
       });
   });
}





</code></pre>
<p><img src="https://img2022.cnblogs.com/blog/139239/202201/139239-20220126114248295-700853080.png" alt="" loading="lazy"></p>
<p>现在我们已经有了用户的基本信息,我们可以集中精力收集单个项目,并另命名为" fillInvoiceItemsInformation"函数。在每个项目执行之前,我们会询问用户是否要添加一个项目。如果他们继续输入" y",那么我们将收集该项目的信息,然后再次询问直到他们键入" n":</p>
<pre><code>function fillInvoiceItemsInformation() {
   const rl = readline.createInterface({
       input: process.stdin,
       output: process.stdout
   });
   var invoiceItemArray = [];
   rl.question('Add item?(y/n): ', (answer) =&gt; {
       switch (answer) {
            case "y":
               console.log("-----------------------\nEnter ItemInformation\n-----------------------");
                rl.question('Quantity: ',(answer) =&gt; {
                   invoiceItemArray.push(answer);
                  rl.question('Details: ',(answer) =&gt; {
                     invoiceItemArray.push(answer);
                        rl.question('UnitPrice: ', (answer) =&gt; {
                           invoiceItemArray.push(answer);
                           invoice.invoiceItems.push({
                               "quantity":invoiceItemArray,
                               "details": invoiceItemArray,
                               "unitPrice": invoiceItemArray
                            });
                            console.log("ItemInformation Added");
                            rl.close();
                           fillInvoiceItemsInformation();
                        });
                  });
                });
                break;
            case "n":
               rl.close();
                return fillExcelFile();
                break;
            default:
                console.log("Incorrectoption, Please enter 'y' or 'n'.");
       }
   });
}

</code></pre>
<h3 id="五填入您的excel-文件">五、填入您的Excel 文件</h3>
<p>在收集所有必需的用户信息后,我们可以将其填入到Excel文件中:</p>
<pre><code>function fillExcelFile() {
   console.log("-----------------------\nFilling in Excelfile\n-----------------------");
   fillBillingInfo();
   fillCompanySetup();
}
function fillBillingInfo() {
   var sheet = wb.getSheet(0);
   sheet.getCell(0, 2).value(invoice.generalInfo.invoiceNumber);
   sheet.getCell(1, 1).value(invoice.generalInfo.invoiceDate);
   sheet.getCell(2, 2).value(invoice.generalInfo.paymentDueDate);
   sheet.getCell(3, 1).value(invoice.generalInfo.customerName);
   sheet.getCell(4, 1).value(invoice.generalInfo.customerCompanyName);
   sheet.getCell(5, 1).value(invoice.generalInfo.customerStreetAddress);
   sheet.getCell(6, 1).value(invoice.generalInfo.customerCityStateZip);
   sheet.getCell(3, 3).value(invoice.generalInfo.invoiceCompanyName);
   sheet.getCell(4, 3).value(invoice.generalInfo.invoiceStreetAddress);
   sheet.getCell(5, 3).value(invoice.generalInfo.invoiceCityStateZip);
}
function fillCompanySetup() {
   var sheet = wb.getSheet(1);
   sheet.getCell(2, 2).value(invoice.companyDetails.yourName);
   sheet.getCell(3, 2).value(invoice.companyDetails.companyName);
   sheet.getCell(4, 2).value(invoice.companyDetails.addressLine1);
   sheet.getCell(5, 2).value(invoice.companyDetails.addressLine2);
   sheet.getCell(6, 2).value(invoice.companyDetails.addressLine3);
   sheet.getCell(7, 2).value(invoice.companyDetails.addressLine4);
   sheet.getCell(8, 2).value(invoice.companyDetails.addressLine5);
   sheet.getCell(9, 2).value(invoice.companyDetails.phone);
   sheet.getCell(10, 2).value(invoice.companyDetails.facsimile);
   sheet.getCell(11, 2).value(invoice.companyDetails.website);
   sheet.getCell(12, 2).value(invoice.companyDetails.email);
   sheet.getCell(13, 2).value(invoice.companyDetails.currencyAbbreviation);
   sheet.getCell(14, 2).value(invoice.companyDetails.beneficiary);
   sheet.getCell(15, 2).value(invoice.companyDetails.bank);
   sheet.getCell(16, 2).value(invoice.companyDetails.bankAddress);
   sheet.getCell(17, 2).value(invoice.companyDetails.accountNumber);
   sheet.getCell(18, 2).value(invoice.companyDetails.routingNumber);
   sheet.getCell(19, 2).value(invoice.companyDetails.payableTo);
}


</code></pre>
<p>为了防止用户添加的数量超过工作表最大行数,我们可以在工作表中自动添加更多行。在设置数组中表单中的项目之前,默认添加行:</p>
<pre><code>function fillInvoiceItems() {
   var sheet = wb.getSheet(0);
   var rowsToAdd = 0;
   if (invoice.invoiceItems.length &gt; 15) {
       rowsToAdd = invoice.invoiceItems.length - 15;
       sheet.addRows(22, rowsToAdd);
   }
   var rowIndex = 8;
   if (invoice.invoiceItems.length &gt;= 1) {
       for (var i = 0; i &lt; invoice.invoiceItems.length; i++) {
            sheet.getCell(rowIndex,1).value(invoice.invoiceItems.quantity);
            sheet.getCell(rowIndex,2).value(invoice.invoiceItems.details);
            sheet.getCell(rowIndex,3).value(invoice.invoiceItems.unitPrice);
            rowIndex++;
       }
   }
}


</code></pre>
<h3 id="六将文档内容从-nodejs-导出到-excel-文件">六、将文档内容从 Node.js 导出到 Excel 文件</h3>
<p>在工作簿中填写完信息后,我们可以将工作簿导出到Excel文件中。为此,我们将使用excelio打开功能。在这种情况下,只需将日期输入文件名即可:</p>
<pre><code>function exportExcelFile() {
   excelIO.save(wb.toJSON(), (data) =&gt; {
       fs.appendFileSync('Invoice' + new Date().valueOf() + '.xlsx', newBuffer(data), function (err) {
            console.log(err);
       });
       console.log("Export success");
   }, (err) =&gt; {
       console.log(err);
   }, { useArrayBuffer: true });
}


</code></pre>
<p>完成的文件将如下所示:</p>
<p><img src="https://img2022.cnblogs.com/blog/139239/202201/139239-20220126114435042-1758350649.png" alt="" loading="lazy"></p>
<p>以上就是第一篇《从服务端生成Excel电子表格(Node.js+SpreadJS)》的全部内容。为了能够解决批量绑定数据源并导出Excel、批量修改大量Excel内容及样式、服务端批量打印以及生成PDF文档等需求,我们提供了更为成熟的官方手段:SpreadJS + GcExcel,该方案提供了比Node.js+SpreadJS更加优秀的性能和稳定性,这就是我们下一篇《从服务端生成Excel电子表格(GcExcel + SpreadJS)》的主要内容,敬请期待。</p>


</div>
<div id="MySignature" role="contentinfo">
    <hr>
<br>
<p style="font-size: 16px; font-family: 微软雅黑, 黑体, Arial; color: #000">本文是由葡萄城技术开发团队发布,转载请注明出处:葡萄城官网</p>
<!--p style="font-size: 16px; font-family: 微软雅黑, 黑体, Arial; color: #000">了解企业级低代码开发平台,请前往活字格
</p><p style="font-size: 16px; font-family: 微软雅黑, 黑体, Arial; color: #000">了解可嵌入您系统的在线 Excel,请前往SpreadJS纯前端表格控件</p>
<p style="font-size: 16px; font-family: 微软雅黑, 黑体, Arial; color: #000">了解嵌入式的商业智能和报表软件,请前往Wyn Enterprise
</p-->

<br><br><br>
来源:https://www.cnblogs.com/powertoolsteam/p/15846009.html
頁: [1]
查看完整版本: 从服务端生成Excel电子表格(Node.js+SpreadJS)