使用 JavaScript 的 xlsx 库,在 Excel 文件的指定列续写指定字符串内容

本文将介绍如何使用 JavaScript 的 xlsx 库,在 Excel 文件的指定列续写指定字符串内容。以下是一个示例函数:

const XLSX = require('xlsx');

function writeStringToColumn(filePath, sheetName, columnName, startRow, endRow, value) {
  // 读取 Excel 文件
  const workbook = XLSX.readFile(filePath);
  const worksheet = workbook.Sheets[sheetName];

  // 获取列的范围
  const range = XLSX.utils.decode_range(worksheet['!ref']);
  const column = XLSX.utils.decode_col(columnName);

  // 遍历指定行范围,续写字符串
  for (let row = startRow; row <= endRow; row++) {
    const cellAddress = XLSX.utils.encode_cell({ r: row, c: column });
    worksheet[cellAddress] = { t: 's', v: value };
  }

  // 保存修改后的 Excel 文件
  XLSX.writeFile(workbook, filePath);
}

使用示例

const filePath = 'path/to/excel.xlsx';
const sheetName = 'Sheet1';
const columnName = 'A';
const startRow = 2;
const endRow = 5;
const value = 'example';

writeStringToColumn(filePath, sheetName, columnName, startRow, endRow, value);

以上代码会将 Excel 文件中 Sheet1 中 A 列的第 2 行到第 5 行续写为 'example'。

JavaScript Excel 操作:在指定列续写字符串

原文地址: http://www.cveoy.top/t/topic/fpHp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录