본문 바로가기

Node.js

[Node.js] How to use xlsx with Typescript / xlsx 사용법

반응형

 

xlsx 를 사용하기 전 엑셀에 CSS 등 꾸미는 것 (배경 색, 정렬 등등) 이 필수라면 xlsx보다 excel.js 를 권합니다! 

(xslx 실컷 사용하다가 css 가 유료인걸 뒤늦게 알고 Exceljs로 옮김)

👇👇👇

https://blckchainetc.tistory.com/entry/Nodejs-Exceljs-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%B4%9D%EC%A0%95%EB%A6%AC-How-to-use-Exceljs-%ED%85%8C%EC%9D%B4%EB%B8%94-%EB%A7%8C%EB%93%A4%EA%B8%B0-insertRows-columns-value-%EB%93%B1

 

[Node.js] Excel.js 사용법 총정리 / How to use Exceljs (테이블 만들기, insertRows, columns, value 등)

이번 프로젝트 중 가장 시간도 오래걸리고 어려웠던 엑셀 파일 만들어 내보내기 를 정리해서 기록으로 남기기 기존에는 xlsx를 익히고 사용했었다가 css가 유료인걸 뒤늦게 알았다.. 👼🏼 찾아

blckchainetc.tistory.com

 

 

설치하기 Installation

 

npm install xlsx

설치 후, 아래와 같이 두 가지의 가져오기 방법이 있다. 

and now you can use XLSX in 2 ways.

 

- require ( default )

const XLSX = require('xlsx');

 

- import 

import * as XLSX from 'xlsx/xlsx.mjs';   // This is what XLSX README says but you can try the next line 
import XLSX from 'xlsx'; 

 

An error can occur when using "import" - [ERROR] Could not find a declaration file for module 'xlsx/xlsx.mjs'

import를 사용할 경우 빨간 줄이 그어지며 아래와 같은 에러가 나왔다. Typescript가 모듈에 대한 type declaration을 찾을 수 없어서 그렇다. 

 

에러 메세지에 나온 해결 방법대로 type을 설치해 보기

To solve the error, you can install the types for the module 

npm install --save-dev @types/module-name

 

그래도 에러가 그대로면 (나의 경우) 해당 모듈은 타입핑을 제공하지 않는 거일 수도 있다. 그럼 '.d.ts' 확장명 파일을 만들어줘야 한다. 현재 ts 파일의 위치에 'module-name.d.ts' 파일을 만들고 아래 코드를 작성한다. 

If the error persists, the module you are importing might not provide typings. In this case, you need to declare the module in a file with a '.d.ts' extension. 

Create a new file named 'module-name.d.ts' next to your regular Typescript fileds add the following code in it. 

declare module 'xlsx/xlsx.mjs';   // <- put module name

요렇게 해주면 impot 해올 때 패키지의 타입을 any로 정해주게 된다. 여기까지 해주니 빨간 에러 줄이 사라졌다 ! -> 근데 나중에 running 시에 문제가 생겨서 그냥 아래처럼 import 해주니까 되었다.

This will se the type of the package to 'any' when importing it. 

Now the error is gone !   -----> still something wrong at the end of running so you can just use as below 

import XLSX form 'xlsx';

It worked ! 

 

 

ReadFile & WriteFile & Stream 을 위한 Import 하기 

* load 'fs' for readFile and writeFile support 

import * as fs from 'fs';
XLSX.set_fs(fs);

set_fs는function이 아니라는 에러 메세지가 나와서 그냥 삭제했다. 

=> It occurs an error saying set_fs is not a function so I just deleted it. 

 

* load 'stream' for stream support 

import { Readable } from 'stream';
XLSX.stream.set_readable(Readable);

 

 

 

 

사용하기 이론 Usage 

대부분 아래와 같은 5가지 단계를 거친다. 단계별로 하나씩 공부해보기 

Most senarios involving spreadsheets and data can be broken into 5 parts. I'm going to go through step by step. 

 

1. 데이터 얻기 Acquire Data 

로컬에 있거나 원격 파일에 있거나 DB, HTML Table, 웹 브라우저에서 프로그램적으로 생성된 데이터 등등 

Data may be stored in local, remote files, databases, HTML Table, or even generated programmatically in the web browser. 

 

2. 데이터 추출 Extract Data

spreadsheet 파일같은 경우, cell 데이터를 읽기위해 raw bytes를 파싱해야 한다. 일반적인 JS데이터는 데이터를 재구성해야 할 수도 있다. 

For spreadsheet files, this involves parsing raw bytes to read the cell data. For general JS data, this involves reshaping the data. 

 

3. 데이터 가공 Process Data

요약된 통계자료를 만드는 것부터 데이터를 깔끔하게 만드는 것까지 포함된 데이터 가공 step은 정말 중요하다. 

From generating summary statistics to cleaning data records, this step is the heart of the problem.

 

4. 데이터 묶기 Package Data

새로운 spreadsheet을 만들거나 JSON.stringify로 연속하거나 또는 XML을 쓰거나 간단히 flattening data를 한다. 

This can involve making a new spreadsheet or serializing with JSON.stringify or writing XML or simply flattening data fro UI tools. 

 

5. 데이터 방출 Release Data 

이렇게 완성된 데이터는 서버에 업로드 될 수 있거나 로컬에 저장될 수 있다. HTML Table 또는 Data grid로 유저에게 보여진다. 

Spreadsheet files can be uploaded to a server or written locally. Data can be presented to users in an HTML Table or data grid. 

 

 

 

 

Step 1, 2 - Acquiring and Extracting Data 

Parsing Workbooks 

 

스프레드시트 바이트로부터 데이터 추출 

Extract data from spreadsheet bytes 

const workbook = XLSX.read(data, opts);

 

로컬 파일로부터 읽고 추출하기 

Read spreadsheet bytes from a local file and extract data 

const workbook = XLSX.readFile(filename, opts);

 

 

Processing JSON and JS Data 

 

Creating a new Workbook 

빈 엑셀북 만들기 (워크시트가 포함된 것이 아님)

It creates an empty workbook with no worksheets.

const workbook = XLSX.utils.book_new();

 

Creating a Worksheet 

워크 시트 만들기 

 

1) AOA (Array of Arrays) 배열의 배열로 만들기 

Create a worksheet from an array of arrays of JS values. 

const worksheet = XLSX.utils.aoa_to_sheet(aoa, opts);
    const worksheet = XLSX.utils.aoa_to_sheet([
        ["A1", "B1", "C1"],
        ["A2", "B2", "C2"],
        ["A3", "B3", "C3"]
    ])
    console.log('worksheet =', worksheet);

 

 

2) JSA (Array of JS objects) Json데이터로 만들기

맨 위에 필드명? 같은 Header row가 생성된다. 

It will generate a header row and one row per object in the array. 

 

const worksheet = XLSX.utils.json_to_sheet(jsa, opts);

 

 

 

Step 3 - Processing Data 

 

워크북에 워크시트 붙이기 / 추가하기

Append a worksheet to a workbook 

 

XLSX.utils.book_append_sheet(workbook, worksheet, sheet_name);

sheet_name으로 어떤 worksheet을 workbook에 붙일지 정할 수 있다. 

여러번 book_append_sheet() 함수를 호출하여 여러개의 worksheets을 붙일 수 있고 같은 이름의 worksheet이 해당 workbook 안에 이미 사용된 적이 있으면 오류를 던진다. 

 

It appends a worksheet to the workbook. The third argument specifies the desired worksheet name. Multiple worksheets can be added to a workbook by calling the function multiple times. If the worksheet name is already used in the workbook, it will throw an error. 

 

When the 4th argument is true : 

const new_name = XLSX.utils.book_append_sheet(workbook, worksheet, name, true);

네 번재 인자값이 True인 경우, name (세 번째 인자값) 이 해당 workbook에 존재하면 자동으로 이름을 분석(?)해서 증가하는 이름을 생성해준다. 

The function will start with the specified worksheet name. If the sheet name exists in the workbook, a new worksheet name will be chosen by finding the name stem and incrementing the counter. 

 

XLSX.utils.book_append_sheet(workbook, sheetA, "Sheet2", true); // Sheet2
XLSX.utils.book_append_sheet(workbook, sheetB, "Sheet2", true); // Sheet3
XLSX.utils.book_append_sheet(workbook, sheetC, "Sheet2", true); // Sheet4
XLSX.utils.book_append_sheet(workbook, sheetD, "Sheet2", true); // Sheet5

 

 

 

 

순서대로 워크시트 이름 나열하기 

List the worksheet names in tab order 

 

const worksheetNames = worbook.SheetNames;

 

 

워크시트 바꾸기 

Replace a Worksheet in place 

 

workbook.Sheets[sheet_name] = new_worksheet;

 

 

 

셀 값을 변경시키기 

Modifying Cell Values 

 

XLSX.utils.sheet_add_aoa(worksheet, [[new_value]], {origin: address});
XLSX.utils.sheet_add.aoa(worksheet, aoa, opts);    // modify multiple cell values in a worksheet 

the first argument : the worksheet 

the secone argument : an array of arrays of values 

the third argument : where cells will be written

 

XLSX.utils.sheet_add_aoa(worksheet, [
  [1],                             // <-- Write 1 to cell B3
  ,                                // <-- Do nothing in row 4
  [/*B5*/, /*C5*/, /*D5*/, "abc"]  // <-- Write "abc" to cell E5
], { origin: "B3" });

 

 

 

 

 

Step 4, 5 - Packaging and Releasing Data 

 

Writing Workbooks

 

Generate spreadsheet bytes(file) from data

const data = XLSX.write(workbook, opts); 

write() 함수는 workbook의 데이터를 메모리 안의 파일로 패키지한다. xlsx 파일이 디폴트로 생성되지만 opts의 bookType으로 변경될 수 있다. 데이터는 binary string, JS string, Uint8Array 또는 Buffer로 저장될 수 있다. 

 

The write method attempts to package data from the workbook into a file in a memory. By default, xlsx files are generated, but that can be controlled with the bookType property of the opts argument. Based on the type option, the data can be stored as a "binary string", JS string Uint8Array or Buffer. 

 

Generate and attempt to save file

XLSX.writeFile(workbook, filename, opts);

writeFile() 함수는 데이터를 패키지해서 새로운 파일로 저장한다. 파일 이름 확장자에 따라 export되는 파일 포맷이 달라진다. 

 

The writeFile method packages the data and attempts to save the new file. The export file format is determined by the extension of filename. 

 

 

 

 

 

xlsx로 엑셀 파일을 만들다가 알게 된 사실!  줄 맞춤이라던지 셀 배경 색 바꾸기 등이 모두 유료버전만 가능했따,,, 👀 그래서 요즘 exceljs 로 많이 갈아타고 있다고 한다. 다음 포스팅은 exceljs로 엑셀 파일 만들고, 저장하는 걸 해봐야겠다. 

 

xlsx library doesn't support aligning contents or changing background colors and so on, it is only possible on the pro version which is not free. That's why lots of people started to use exceljs library instead of xlsx. my next posting will be about exceljs ! 

 

 

 

exceljs 사용법 

https://blckchainetc.tistory.com/entry/Nodejs-Exceljs-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%B4%9D%EC%A0%95%EB%A6%AC-How-to-use-Exceljs-%ED%85%8C%EC%9D%B4%EB%B8%94-%EB%A7%8C%EB%93%A4%EA%B8%B0-insertRows-columns-value-%EB%93%B1

 

[Node.js] Excel.js 사용법 총정리 / How to use Exceljs (테이블 만들기, insertRows, columns, value 등)

이번 프로젝트 중 가장 시간도 오래걸리고 어려웠던 엑셀 파일 만들어 내보내기 를 정리해서 기록으로 남기기 기존에는 xlsx를 익히고 사용했었다가 css가 유료인걸 뒤늦게 알았다.. 👼🏼 찾아

blckchainetc.tistory.com

 

 

 

 

Reference : https://www.npmjs.com/package/xlsx

https://bobbyhadz.com/blog/typescript-could-not-find-a-declaration-file-for-module

 

 

반응형