使用nodejs/exceljs读取、操作、写入excel文件

现在edge已经不支持activexobject了,如果想用javascript操作excel文件,基本上只能用nodejs了。下面的代码就是用nodejs操作excel文件的可用方法,读取每个cell,设置颜色。

javascript 复制代码
// save this content as excel.js file
// # npm i exceljs
// # node excel.js

const ExcelJS = require('exceljs');


async function ProcessSheet(sheet)
{
  let rows=sheet.rowCount, cols=sheet.columnCount;
  console.log(`  ${rows} rows, ${cols} cols`);
  for(let row=1; row<=rows; row++)
  {
    let r=sheet.getRow(row);
    if(row==1) { if(!r.font) r.font={};  r.font.color={ argb: 'FFFF0000'};  }
    for(let col=1; col<=cols; col++)
    {
      let cell=r.getCell(col); let v=cell.value;
      console.log(`  [${row}, ${col}] ${v}`);
    }
  }  
}


async function ProcessFile(ExcelFilePath)
{
  const workbook = new ExcelJS.Workbook();
  await workbook.xlsx.readFile(ExcelFilePath);
  let sheets=workbook.worksheets, sheetsCount=sheets.length;
  for(let sheet_index=0; sheet_index<sheetsCount; sheet_index++)
  {
    let sheet=sheets[sheet_index];    
    console.log(`sheet ${sheet.id}: ${sheet.name}`);
    await ProcessSheet(sheet);
  }
  
  // Iterate over all sheets
  // Note: workbook.worksheets.forEach will still work but this is better
  //--workbook.eachSheet(function(worksheet, sheetId) {     });

  // fetch sheet by name
  //--const worksheet2 = workbook.getWorksheet('My Sheet');

  // fetch sheet by id
  //--const worksheet3 = workbook.getWorksheet(1);


  await workbook.xlsx.writeFile(ExcelFilePath);
}


function CreateFile()
{
  const workbook = new ExcelJS.Workbook();

  workbook.creator = 'Me';
  workbook.lastModifiedBy = 'Her';
  workbook.created = new Date(1985, 8, 30);
  workbook.modified = new Date();
  workbook.lastPrinted = new Date(2016, 9, 27);
  
  const sheet = workbook.addWorksheet('My Sheet');
  workbook.removeWorksheet(sheet.id);
}

ProcessFile("C:\\Users\\Qiuzen\\Desktop\\艺术快递.xlsx");
相关推荐
华洛39 分钟前
利好打工人,openclaw不是企业提效工具,而是个人助理
前端·javascript·产品经理
xkxnq1 小时前
第六阶段:Vue生态高级整合与优化(第93天)Element Plus进阶:自定义主题(变量覆盖)+ 全局配置与组件按需加载优化
前端·javascript·vue.js
A黄俊辉A2 小时前
vue css中 :global的使用
前端·javascript·vue.js
灵感__idea2 小时前
Hello 算法:复杂问题的应对策略
前端·javascript·算法
chushiyunen3 小时前
python中的内置属性 todo
开发语言·javascript·python
soso19683 小时前
JavaScript性能调优实战案例
javascript
Moment4 小时前
前端工程化 + AI 赋能,从需求到运维一条龙怎么搭 ❓❓❓
前端·javascript·面试
Joker Zxc4 小时前
【前端基础(Javascript部分)】6、用JavaScript的递归函数和for循环,计算斐波那契数列的第 n 项值
开发语言·前端·javascript
Highcharts.js4 小时前
React 图表如何实现下钻(Drilldown)效果
开发语言·前端·javascript·react.js·前端框架·数据可视化·highcharts
chushiyunen5 小时前
python中的魔术方法(双下划线)
前端·javascript·python