Đọc file excel TypeScript

Phần đầu tiên của hướng dẫn này chỉ là về việc thiết lập cấu hình theo cách chuyên nghiệp hơn một chút so với chỉ npm init. Bạn có thể tìm thấy ở đây https. //Trung bình. com/@andrewallison/a-simple-project-with-typescript-nodejs-85e48616b1

Mã nguồn có thể được lấy ở đây. Tôi đã gắn thẻ nó là P1 để bạn có thể chuyển thẳng đến nơi bài viết này bắt đầu nếu bạn cần

https. //github. com/AndrewAllison/read-excel/releases/tag/P1

Phần 2

Được rồi, hãy bắt đầu phần thứ hai của điều này bằng cách cài đặt các gói cần thiết để đọc tệp excel và viết nó ra JSON

 npm i exceljs csvtojson

ExcelJs - Đây là một trong những thư viện tốt hơn nếu được tìm thấy để giúp thao tác các tệp Excel. Tìm hiểu thêm về nó tại đây https. //www. npmjs. com/gói/exceljs

CsvToJson — Công cụ này giúp chuyển đổi excel thành JSON thông qua phương tiện csv thực sự đơn giản https. //www. npmjs. com/gói/csvtojson

GHI CHÚ. Điều này dựa trên một tệp Excel tương đối nhỏ và đơn giản. Nếu tệp lớn, bạn có thể muốn sử dụng một luồng thay vì đọc tất cả vào bộ nhớ trong một lần. Có một bài viết SO tuyệt vời về điều này và tôi có thể thực hiện một số bài viết trong tương lai về nó. https. // stackoverflow. com/câu hỏi/69866039/parse-excel-file-and-create-json-format-in-exceljs-on-nodejs

OK, chúng ta hãy lấy phần quan trọng của dự án

Tạo một tệp mới

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
6 Đây chỉ là một nơi gần hơn để đặt một số phương thức trong trường hợp tại một số điểm chúng cần được sử dụng lại. Gửi nó với đoạn mã sau

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };

Hai phương thức sử dụng trong tệp này là `writeToTempFile` dùng để đọc tệp Excel và ghi tệp đó vào csv tạm thời và `readFromFile` sẽ đọc tệp tạm thời và tạo đối tượng json từ tệp đó

Cập nhật tiếp theo tệp

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
7 với nội dung sau

import * as fs from 'fs';
import * as path from 'path';
import { readFromFile, tempFolderPath, writeToTempFile } from './file-utils';

const run = async [] => {
return new Promise[async [resolve] => {
const originalExcelFile = path.join[__dirname, '../', 'data', 'books.xlsx'];
const tempCsvFilePath = path.join[tempFolderPath, 'temp_books.csv'];
const jsonWriteFile = path.join[tempFolderPath, 'books.json'];

console.log[`Reading file from: ${originalExcelFile}`];
await writeToTempFile[originalExcelFile, tempCsvFilePath];
const jsonObj = [await readFromFile[tempCsvFilePath]] as any[];

console.log[`Writing file ${jsonWriteFile}`];
const jsonWrite = fs.createWriteStream[jsonWriteFile];
jsonWrite.write[JSON.stringify[jsonObj, null, 2]];

return resolve[{
success: true,
message: `File wrote complete: Items Stored: ${jsonObj.length}`,
}];
}];
};

run[]
.catch[[e] => console.error[e]]
.then[[c] => console.log['Complete', c]];

Bạn cũng sẽ cần tạo một thư mục có tên là

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
8 trong thư mục gốc của dự án và thêm tệp ví dụ xlsx. Đó là một tệp sách tôi đã lấy từ ý chính. Tải xuống từ repo GitHub https. //github. com/AndrewAllison/read-excel/blob/main/data/books. xlsx, hãy nhấp vào nút "Tải xuống" và đảm bảo rằng nó nằm trong thư mục dữ liệu ở thư mục gốc của dự án của bạn

Cấu trúc tệp sẽ trông giống như

ĐI NÀO

Chạy lại lệnh

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
0 và xem nó tạo ra các tệp một cách kỳ diệu. Nên có một cuốn sách. json và một cuốn sách. csv trong thư mục tạm thời như trên. Đây sẽ không phải là một phần của các tệp đã cam kết vì chúng ở vị trí tạm thời. Điều này là do chúng tôi muốn tiếp tục tạo lại chúng khi mọi thứ thay đổi nhưng bạn có thể thêm chúng nếu muốn

Cuối cùng, chúng tôi sẽ thực hiện lệnh

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
1, sau đó là
import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
2 điền thông tin chi tiết và thực hiện lệnh
import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
3 để đẩy mã của chúng tôi lên github

Bước cuối cùng là nếu bạn đang làm việc theo phong cách git flow và đang chơi trên nhánh

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
4, hãy tạo một yêu cầu kéo và hợp nhất tất cả lại vào nhánh
import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
5. Sẽ có một biểu ngữ màu xanh lá cây trong Github cho bạn biết rằng bạn đã thúc đẩy phát triển và yêu cầu bạn hợp nhất trở lại chính

Kéo Yêu cầu để hợp nhất trở lại phần thưởng chính

Chỉ cần ném cái này vào như một phần thưởng nhỏ

npm i -D dotenv-cli standard-version conventional-github-releaser

Vì vậy, bạn có thể theo dõi phiên bản của gói và các thay đổi một cách gọn gàng, khá dễ dàng để sử dụng các gói sau và thiết lập một số lệnh script. Tôi sẽ không tự động hóa hoàn toàn việc này vì nó nằm ngoài phạm vi của bài viết này nhưng sẽ không mất nhiều thời gian.

Phiên bản tiêu chuẩn

phiên bản tiêu chuẩn không được dùng nữa. Nếu bạn là người dùng GitHub, tôi khuyên bạn nên phát hành-vui lòng thay thế. Tôi khuyến khích…

www. npmjs. com

thông thường-github-releaser

Tạo bản phát hành GitHub mới từ siêu dữ liệu git. Lưu ý Bạn không phải sử dụng quy ước cam kết góc. Cho điều tốt nhất…

www. npmjs. com

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
0

tạo một tệp

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
6 trong thư mục gốc của dự án của bạn. Lấy mã thông báo github bằng cách làm theo các hướng dẫn sau https. //github. blog/2013-05-16-personal-api-tokens/

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
2

Từ đó, bạn có thể chạy

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
7, bạn sẽ nhận được một số đầu ra tương tự như

đầu ra từ bản phát hành git

Bạn cũng có thể làm điều này trên một nhánh phát hành nếu bạn muốn thực sự nâng cấp nó lên một bậc. Có cả một bài viết đáng giá về tự động hóa quy trình phát hành. Tôi có thể thử và sớm tìm đến một trong số đó

Thực hiện lệnh sau

import * as csvToJson from 'csvtojson';
import * as ExcelJS from 'exceljs';
import * as fs from 'fs';
import * as path from 'path';

const tempFolderPath = path.join[__dirname, '../', 'temp'];

const readFromFile = async [filePath: string] => {
return new Promise[[resolve] => {
csvToJson[]
.fromFile[filePath]
.then[[jsonObj] => {
return resolve[jsonObj];
}];
}];
};

const writeToTempFile = async [
originalExcelFile: string,
tempCsvFilePath: string,
]: Promise => {
if [!fs.existsSync[tempFolderPath]] {
fs.mkdirSync[tempFolderPath];
}

const workbook = new ExcelJS.Workbook[];
await workbook.xlsx.readFile[originalExcelFile];

const writeStream = fs.createWriteStream[tempCsvFilePath];
await workbook.csv.write[writeStream, { sheetName: 'books' }];
};

export { tempFolderPath, readFromFile, writeToTempFile };
4

Bước tiếp theo, tôi không chắc liệu mình có làm đúng hay không vì đã có ghi chú phát hành nên tôi sẽ tìm cách khắc phục điều này đúng cách trong một bài viết sau. Để làm cho chúng hoạt động, tôi đã thực hiện một yêu cầu kéo và hợp nhất mọi thứ vào chính. The ran ________ 18 Bạn sẽ nhận được một số đầu ra khá

Các ghi chú phát hành sau đó đã xuất hiện

Ghi chú phát hành trong github

Bạn có thể xem rõ hơn tại https. //github. com/AndrewAllison/read-excel/phát hành

suy nghĩ

Là một người đã làm việc nhiều năm trong lĩnh vực công nghệ, tôi chưa bao giờ đưa ra nhiều nội dung vì tôi luôn muốn nó phải thật hoàn hảo trước khi phát hành. Lần này, tôi đang cố gắng đưa mọi thứ ra khỏi đó ngay cả khi nó không . Vì vậy, hãy thoải mái đưa ra phản hồi và đưa ra yêu cầu nhưng hãy nhẹ nhàng và tử tế. Tôi chỉ đơn giản là cố gắng giúp đỡ người khác bằng những thứ tôi biết

Người giới thiệu

Chúng tôi đã lấy một số nội dung dựa trên google để sử dụng làm bảng tính demo. Chúng tôi đã nhận nó từ đây. https. //ý chính. githubusercontent. com/jaidevd/23aef12e9bf56c618c41/raw/c05e98672b8d52fa0cb94aad80f75eb78342e5d4/books. csv

Làm cách nào để đọc dữ liệu từ tệp Excel trong TypeScript?

Hãy mở tệp mẫu và xem có gì bên trong. .
Nội dung file Excel cần đọc
Hiển thị nội dung của tệp Excel trong bảng điều khiển
Xem cấu trúc của một ô công thức
Nội dung của Excel được trích xuất tốt và hiển thị trong bảng điều khiển

Làm cách nào để đọc một tệp Excel trong góc?

Dưới đây là các bước để nhập và xuất bảng tính Excel trong Angular. .
Cài đặt thành phần SpreadJS trong ứng dụng của bạn
Khởi tạo thành phần SpreadJS
Tạo một yếu tố đầu vào chấp nhận các tệp XLSX
Thêm mã nhập khẩu
Thêm mã xuất khẩu

Làm cách nào để đọc tệp Excel JavaScript?

Cách nhập và xuất Excel XLSX bằng JavaScript .
Thiết lập Dự án Bảng tính JavaScript
Thêm mã nhập Excel
Thêm dữ liệu vào tệp Excel đã nhập
Thêm một biểu đồ thu nhỏ
Thêm mã xuất Excel

Làm cách nào để đọc tệp xls trong nodejs?

Giải thích. Đầu tiên, mô-đun npm được bao gồm trong phần đọc. js và sau đó tệp excel được đọc vào sổ làm việc i. e hằng số trong chương trình trên . Một vòng lặp for được chạy cho đến khi kết thúc tệp excel bắt đầu từ trang đầu tiên.

Chủ Đề