Created
February 4, 2023 07:06
-
-
Save wusuopu/ba5c372518a53303ff7bc09f90eea37b to your computer and use it in GitHub Desktop.
convert xls to xlsx by nodejs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.npmjs.com/package/xlsx#installation | |
const xlsx = require('xlsx') | |
const fs = require('fs') | |
const Path = require('path') | |
const printHelp = () => { | |
console.log('Usage: convert.js <input.xls> [<output>]') | |
} | |
const parseOutput = (input, output) => { | |
let outDir | |
let i = Path.parse(input) | |
if (output) { | |
let o = Path.parse(output) | |
if (o.ext === '.xlsx') { | |
return output | |
} | |
// 指定的是一个目录 | |
outDir = output | |
} else { | |
outDir = i.dir | |
} | |
let filename = Path.join(outDir, `${i.name}.xlsx`) | |
if (fs.existsSync(filename)) { | |
filename = Path.join(outDir, `${i.name}-${new Date().toJSON().replace(/[-:]/g, '')}.xlsx`) | |
} | |
return filename | |
} | |
const convert = (input, output) => { | |
const file = xlsx.readFileSync(input, { type: 'file'}) | |
output = parseOutput(input, output) | |
xlsx.writeFileSync(file, output, { type: 'file'}) | |
console.log(`convert '${input}' --> '${output}'`) | |
} | |
const main = async () => { | |
const input = process.argv[2] | |
const output = process.argv[3] | |
if (!input) { | |
printHelp() | |
console.error('缺少 xls 文件参数'); | |
process.exit(1) | |
} | |
if (!input.endsWith('.xls')) { | |
console.error('不是 xls 文件'); | |
process.exit(1) | |
} | |
if (!fs.existsSync(input)) { | |
console.error(`文件不存在 ${input}`); | |
process.exit(1) | |
} | |
convert(input, output) | |
} | |
if (require.main === module) { | |
main() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment