nodejs 将excel 转CSV 再转json文件 整理数据
const XLSX = require('xlsx');
const fs = require('fs');
const workbook = XLSX.readFile('base.xlsx');
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const csv = XLSX.utils.sheet_to_csv(worksheet);
fs.writeFileSync('output.csv', csv);
index.ts
import { CSV } from './CSV';
import * as fs from 'fs';
const csv = fs.readFileSync('output.csv');
const data = CSV.parse(csv.toString(), ',');
console.log(data);
fs.writeFileSync('testData.json', JSON.stringify(data));
CSV.ts
export class CSV
{
private static cursor:number;
private static count:number;
private static content:string;
private static endline:number;
private static readonly REGQUOTE:RegExp = /""/g;
public static parse(str:string,delimiter:string):{rows:any[], numClos:number}
{
if(!str)return null;
let rows:any[] = [];
let collen:number = 1;
let row:any = null;
let index:number;
CSV.content = str;
CSV.count = str.length;
CSV.cursor = 0;
while(CSV.cursor < CSV.count)
{
row = {};
index = 0;
let online:boolean = true;
let start:number;
while(online)
{
let char:string = CSV.content.charAt(CSV.cursor);
let part:string = "";
if(char == '"')
{
CSV.cursor ++;
start = CSV.cursor;
CSV.closeQuote();
part = CSV.content.substring(start, CSV.cursor - 1).replace(CSV.REGQUOTE, '"');
}
start = CSV.cursor;
online = CSV.nextDelimit(delimiter);
part += CSV.content.substring(start, CSV.endline).replace(CSV.REGQUOTE, '"');
row[index] = part;
index ++;
}
collen = collen < index ? index : collen;
rows.push(row);
}
CSV.content = null;
return {rows:rows, numClos:collen};
}
private static nextDelimit(delimiter:string):boolean
{
while(CSV.cursor < CSV.count)
{
let char:string = CSV.content.charAt(CSV.cursor);
if(char == delimiter)
{
CSV.endline = CSV.cursor;
CSV.cursor ++;
return true;
}
if(char == "\r" || char == "\n")
{
CSV.endline = CSV.cursor;
while(char == "\r" || char == "\n")
{
CSV.cursor ++;
char = CSV.content.charAt(CSV.cursor);
}
return false;
}
CSV.cursor ++;
}
CSV.endline = CSV.count;
return false;
}
private static closeQuote():void
{
while(CSV.cursor < CSV.count)
{
let char:string = CSV.content.charAt(CSV.cursor);
if(char == '"')
{
if((CSV.cursor = (CSV.cursor + 1)) < CSV.count)
{
if(CSV.content.charAt(CSV.cursor) == '"')
{
CSV.cursor ++;
continue;
}
break;
}
}
CSV.cursor ++;
}
}
}