vue对excel模板文件进行更新给所有单元加上边框
要给excel模板文件中的所有单元格加上边框,可以使用以下步骤:
- 安装依赖
npm install xlsx
- 导入依赖
import XLSX from 'xlsx'
- 加载excel文件
const workbook = XLSX.readFile('path/to/excel/file.xlsx')
- 获取第一个sheet
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
- 获取单元格范围
const range = XLSX.utils.decode_range(worksheet['!ref'])
- 循环遍历单元格,给每个单元格加上边框
for (let R = range.s.r; R <= range.e.r; ++R) {
for (let C = range.s.c; C <= range.e.c; ++C) {
const cellAddress = XLSX.utils.encode_cell({ r: R, c: C })
const cell = worksheet[cellAddress]
if (!cell) continue
const border = {
top: { style: 'thin' },
bottom: { style: 'thin' },
left: { style: 'thin' },
right: { style: 'thin' }
}
cell.s = { border }
}
}
- 保存excel文件
XLSX.writeFile(workbook, 'path/to/new/excel/file.xlsx')
完整代码示例:
import XLSX from 'xlsx'
const addBorder = () => {
const workbook = XLSX.readFile('path/to/excel/file.xlsx')
const sheetName = workbook.SheetNames[0]
const worksheet = workbook.Sheets[sheetName]
const range = XLSX.utils.decode_range(worksheet['!ref'])
for (let R = range.s.r; R <= range.e.r; ++R) {
for (let C = range.s.c; C <= range.e.c; ++C) {
const cellAddress = XLSX.utils.encode_cell({ r: R, c: C })
const cell = worksheet[cellAddress]
if (!cell) continue
const border = {
top: { style: 'thin' },
bottom: { style: 'thin' },
left: { style: 'thin' },
right: { style: 'thin' }
}
cell.s = { border }
}
}
XLSX.writeFile(workbook, 'path/to/new/excel/file.xlsx')
}
addBorder()
``
原文地址: https://www.cveoy.top/t/topic/hhXd 著作权归作者所有。请勿转载和采集!