Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'node-xlsx' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
const speedTest = require('speedtest-net');
// const speedTest = require('./speedtest/index')
require('draftlog').into(console)
const axios = require('axios')
const node_xlsx = require('node-xlsx')
const fs = require('fs')
const path = require('path')
const moment = require('moment')
const EC = "127.0.0.1:9090" // 外部控制器 External Controller
const TIME = 10 // 测试时间,单位秒
const PROXY = "http://127.0.0.1:7890" // Clash的http代理
let xlsx = node_xlsx.default
let startTesting = async (id) => {
return new Promise((resolve, reject) => {
var test = speedTest({ maxTime: TIME * 1000, serverId: id, proxy: PROXY });
// test.on('data', data => {
// // console.log('data:', data)
// resolve(data)
// });
let tid = setTimeout(() => {
resolve({ speeds: { download: '-', upload: '-' }, server: { ping: '-', country: '-' } });
}, (10 + TIME) * 1000 );
test.on('downloadspeed', speed => {
clearTimeout(tid)
module.exports = function () {
const xlsxBuffer = xlsx.parse(fs.readFileSync(`${process.cwd()}${path.sep}${config.prefix}_i18n.xlsx`));
const callDef = config.customCall;
let successCount = 0;
const notMatchZhArr = [];
const writeFileList = [];
const newChnMap = {};
xlsxBuffer[0].data.slice(1).reduce((cur, next) => {
if (!newChnMap[next[2]]) {
newChnMap[next[3]] = next[2];
}
}, []);
const files = utils.getFiles();
files.map((file, i) => {
// 如果是en.js文件,则跳过,后面和zh-cn.js一起处理
if (/i18n\/en\.js$/g.test(file)) {
return;
}
const xlsx = require('node-xlsx')
const fs = require('fs')
// Parse a buffer
const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/index.xlsx`));
// Parse a file
const workSheetsFromFile = xlsx.parse(`${__dirname}/index.xlsx`);
console.log(workSheetsFromBuffer)
console.log(workSheetsFromFile)
const data = [
[1, 2, 3],
[true, false, null, 'sheetjs'],
['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
['baz', null, 'qux']
]
// Returns a buffer
const buffer = xlsx.build([{name: "mySheetName", data: data}]);
console.log(buffer)
function excel2json(res,excelPath){
// var xlsx = require('node-xlsx');
// var fs = require('fs');
//读取文件内容
console.log('------11122-',excelPath)
let _excelPath = path.resolve(__dirname, '../'+excelPath);
// let obj = xlsx.parse(__dirname+'./../'+excelPath); //2次上传路径 经常解析错误。(目测是文件写入需要时间)
let obj = xlsx.parse(_excelPath); //2次上传路径 经常解析错误。(目测是文件写入需要时间)
let excelObj=obj[0].data;
// console.log('解析的json--------',excelObj);
/*[ [ '时间', '公司入款', '线上支付', '人工存入', '充值合计' ],
[ '2017-9-17', '33366', '22', '111', '466' ],
[ '2017-9-19', '100190', '1', '1', '3' ],
[ '2017-9-18', '2', '2', '2', '6' ] ]*/
for(var i = 1, len = excelObj.length;i < len; i++) {
//定义提交入参
let insertData = {};
let item = excelObj[i];
for(j in item){
insertData[arr[j]] = item[j]
fs.rename(uploadedPath, dstPath, function(err) {
if(err){
console.log('rename error: ' + err);
} else {
console.log('rename ok');
//读取文件内容
var obj = xlsx.parse(dstPath);
// console.log(obj[0].data);
var sheet = obj[0];
// console.log(sheet);
var datas = sheet.data;
console.log(datas[0]);
datas.splice(0,1)//去除头部: 序号 公众号 ID 分类 粉丝数/w 头条/元 二条/元 三条/元 四条/元 备注
// 是否开通评论功能 阅读量 是否认证 媒体手机 媒体QQ 折扣 下次更新时间 商务对接
//console.log(datas);
var model_arr = datas.reduce(gzhModel.gzhReducer,[]);
//console.log(model_arr);
//console.log(model_arr.length);
//gzhDao.add(model_arr,res,next);
res.json({"data":"导入成功"+model_arr.length+"条微信报价单数据","errorMsg":"","success":true,"totalCount":model_arr.length});
}
});
const workSheetsFromBuffer = xlsx.parse(fs.readFileSync(`${__dirname}/index.xlsx`));
// Parse a file
const workSheetsFromFile = xlsx.parse(`${__dirname}/index.xlsx`);
console.log(workSheetsFromBuffer)
console.log(workSheetsFromFile)
const data = [
[1, 2, 3],
[true, false, null, 'sheetjs'],
['foo', 'bar', new Date('2014-02-19T14:30Z'), '0.3'],
['baz', null, 'qux']
]
// Returns a buffer
const buffer = xlsx.build([{name: "mySheetName", data: data}]);
console.log(buffer)
fs.writeFile("test.xlsx", buffer, "binary",function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
function createRow(index) {
let row = [];
row.push(data.xmlImages[index] || '');
row.push(data.folderImages[index] || '');
row.push(data.copiedImages[index] || '');
row.push(data.skippedImages[index] || '');
return row;
}
const rows = [];
rows.push(headers);
for (let i = 0, l = totalLines; i < l; i++) {
rows.push(createRow(i));
}
const xlsBuffer = xlsx.build([{name: 'exportSFCCResults', data: rows}]);
// If extension is missing, we fallback to CSV
if (path.extname(outputFile) === '') {
outputFile = outputFile + '.csv';
}
// Create the worksheet
return fs.outputFile(outputFile, xlsBuffer).then(() => {
const results = performance.stop();
console.log(`Finished '${chalk.cyan('Export Excel report')}' after ${chalk.magenta(results.time + 'ms')}`);
return {};
});
}
function writeXlsx(cacheKey, queryResult) {
// loop through rows and build out an array of arrays
const resultArray = [];
resultArray.push(queryResult.fields);
for (let i = 0; i < queryResult.rows.length; i++) {
const row = [];
for (let c = 0; c < queryResult.fields.length; c++) {
const fieldName = queryResult.fields[c];
row.push(queryResult.rows[i][fieldName]);
}
resultArray.push(row);
}
const xlsxBuffer = xlsx.build([{ name: 'query-results', data: resultArray }]);
return new Promise(resolve => {
fs.writeFile(xlsxFilePath(cacheKey), xlsxBuffer, function(err) {
// if there's an error log it but otherwise continue on
// we can still send results even if download file failed to create
if (err) {
console.log(err);
}
return resolve();
});
});
}
const Excel = require('node-xlsx').default
const fs = require('fs')
const path = require('path')
const mkdirsSync = require('./utils').mkdirsSync
const chalk = require('chalk')
const Log = console.log
const Warn = console.warn
const Error = console.error
module.exports = function (excelPath, jsPath, projectPath) {
///////// START /////////
let startTime = Date.now()
// File path must end with .xlsx
excelPath = excelPath.endsWith('.xlsx') ? excelPath : excelPath + '.xlsx'
// Read from excel
let inputData = []
try {
// noop
} finally {
global._cacheCleared = true
}
}
inputData = Excel.parse(tmpFilePath)[0].data
} catch (e) {
try {
inputData = Excel.parse(filePath)[0].data
} catch (e) {
Warn(chalk.yellow(
chalk.bgYellow.black(' WARN '),
'Excel file not exist'
))
mkdirsSync(path.dirname(filePath))
fs.writeFileSync(filePath, Excel.build([{name: path.basename(filePath, '.xlsx'), data: null}]))
}
}
Log(chalk('> ',
'Length of i18n before reading from project:',
chalk.cyan(inputData.length)
))
// zh keys
let i18ns = inputData.map(row => row[0]).filter(col => col !== 'index')
const i18nReg = /\$t\(['"`](.*?)['"`](?:\s*,.*?)?\)/
// Get all i18ns from project
traversingDirectory(rootPath, function (fileContent, filePath, fileDir) {
if (/\.(vue|js)$/.test(filePath)) {
let matchList = fileContent.match(RegExp(i18nReg, 'gm'))
if (matchList) {
i18ns = i18ns.concat(matchList.map(item => item.replace(i18nReg, '$1')))
}