STUDY/React

엑셀 HTML로 불러오기

_JJ_ 2023. 5. 16. 09:39

업무 중 엑셀 파일을 pdf로 작업 변환할 일이 생겼는데, 이걸 코드를 짜서 자동화하면 어떨까 하는 생각이 들었다.

모종의 이유로 그럴 필요가 없어졌지만, 평소 코드로 엑셀파일은 다뤄본 적이 없던지라

알아보면서 알게 된 것들을 한번 정리를 해두려고 한다. 테스트는 리액트로 작성했다.


exceljs vs sheetjs

주로 엑셀 관련해서 많이 쓰는 라이브러리는 exceljs와 sheetjs 두 가지가 있었다.

다운로드 수가 sheetjs가 더 많았고, xlsx, csv, txt, html, json 등 지원하는 파일 포맷이 다양해서 sheetjs로 알아보게 되었다.

border style을 설정하려면 pro를 구매해야 된다는 말이 있었지만 어차피 파일 변환만 하면 되는 거 아니야? 간단할 것 같은데~ 하는 안일한 생각과 함께 ㅎㅎ..

 

sheetjs 공식 사이트

https://docs.sheetjs.com/docs/

 

Overview | SheetJS Community Edition

SheetJS Community Edition offers battle-tested open-source solutions for

docs.sheetjs.com

 

setting

npm i --save https://cdn.sheetjs.com/xlsx-0.19.1/xlsx-0.19.1.tgz

import { read, utils } from "xlsx";

 

<>
      <input
        type="file"
        id="excel"
        accept=".xls,.xlsx"
        onChange={readExcel}
        multiple="multiple"
      />

      <div ref={tbl} dangerouslySetInnerHTML={{ __html }} />
</>

로컬에 있는 엑셀 파일 중 선택한 파일 정보를 읽어와서 html로 뿌린다.

  const [__html, setHtml] = useState("");
  const tbl = useRef(null);

  const readExcel = async (e) => {
    const file = e.target.files[0];
    const data = await file.arrayBuffer();
    /* data is an ArrayBuffer */
    const wb = read(data);
    const ws = wb.Sheets[wb.SheetNames[0]]; // get the first worksheet
    const dat = utils.sheet_to_json(ws); // generate objects
    setPres(dat); // update state
    const dataHtml = utils.sheet_to_html(ws); // generate HTML
    setHtml(dataHtml); // update state
  };

후다닥 써보느라 변수명을 너무 대충 지어서 부끄럽지만,,

작성하고 파일 선택을 하면 내용이 html로 담겨져서 나온다.

스타일 같은 거 일체 없고 그냥 내용만 덜렁 나온다.

내 생각은 엑셀에 스타일링 다 되어있고 확장자만 바꾸는 거니 간단할 거라 생각했는데

엑셀을 pdf로 바꾸는 것도 jspdf같은 라이브러리를 깔아서 내용을 넘겨서 해야 되는 것 같다. 쉬운 게 없다..