使用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");
相关推荐
新*2 小时前
从一段 WebSocket 代码聊开:bytes 不是 zlib、binaryType 决定一切,15MB 大消息的零拷贝优化
javascript·python·websocket·性能优化·blob·zlib·arraybuffer
OpsEye3 小时前
别再挨个充会员了:多模型编码,最麻烦的从来不是选模型
javascript·ai编程
学以智用4 小时前
jsencrypt.js 完整详解
javascript
2601_967980116 小时前
Python自动化办公:模块、库与样式调整教程
python·excel·自动化办公·openpyxl·样式调整
Hilaku7 小时前
你们公司有 35 岁以上的前端吗?
前端·javascript·程序员
鸿蒙开发8 小时前
小程序存档写到一半怎么办?双槽保存与损坏恢复实战
前端·javascript·react.js
知忆_IS8 小时前
TerriaMap 开发实战04:MVT数据自定义符号化 - terriajs源码修改
javascript·webgis·terriamap·terriajs
用户0332126663679 小时前
使用 Python 轻松加密或解密 Excel 文档
python·excel
云上工程笔记11 小时前
SRT字幕一键转手绘动画:srt-whiteboard-animation的复刻实录
大数据·开发语言·javascript·人工智能·机器学习
FungLeo11 小时前
成为全栈·Vue管理后台篇·<scriptsetup>:把页面拆成可读、可测的 Vue 组件
前端·javascript·vue.js·typescript·前端组件化·composition api·vue sfc