! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

웹 응용 프로그램에 Angular Excel XLSX 뷰어를 추가하는 방법 > 온라인 스터디

본문 바로가기

기초가이드 웹 응용 프로그램에 Angular Excel XLSX 뷰어를 추가하는 방법

페이지 정보

작성자 GrapeCity 작성일 2023-07-11 14:38 조회 127회 댓글 0건

본문

첨부파일

클라이언트 컨트롤인 JavaScript 스프레드시트, SpreadJS는 Angular 등 여러 프레임워크와 함께 사용할 수 있습니다.


이번 스터디에서는 응용 프로그램에 SpreadJS와 Angular 15를 사용하여 XLSX 뷰어를 추가하고 사용자가 쉽게 Excel 파일을 볼 수 있도록 허용하는 방법을 설명합니다.


Angular Excel XLSX 뷰어

따라 하려면 샘플을 다운로드해 주세요!



Angular 설치 


Angular를 사용하려면 먼저 설치해야 합니다.

Angular를 설치하려면 명령 프롬프트를 사용하여 Angular CLI를 설치해 주세요.

npm install -g @angular/cli


최신 Angular가 전체적으로 설치됩니다.



새 프로젝트 만들기 


이제 터미널을 사용하여 새 프로젝트를 만들 수 있습니다.

ng new spread-sheets-angular-cli
cd spread-sheets-angular-cli


해당 프로젝트에서 NPM을 사용하여 프로젝트에 필수 SpreadJS 라이브러리를 추가합니다.

npm install @grapecity/spread-sheets
npm install @grapecity/spread-sheets-angular


또한 angular.json 파일에 스타일을 추가해야 합니다.

{
  ...
  "projects":{
    "spread-sheets-angular-cli":{
      ...
      "architect":{
        ...
        "build":{
          ...
          options:{
            ...
            "styles": [
              "node_modules/@grapecity/spread-sheets/styles/gc.spread.sheets.excel2016darkGray.css"
            ],
            ...
          }
          ...
        }
        ...
      }
      ...
    }
  }
  ...
}


코드를 추가하여 SpreadJS를 응용 프로그램에 추가할 수 있습니다.



SpreadJS 코드 추가 


추가해야 하는 첫 번째 SpreadJS 코드는 src>app>app.module.ts 파일에 있습니다.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { SpreadSheetsModule } from "@grapecity/spread-sheets-angular";
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule,SpreadSheetsModule],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }


앱 모듈을 위한 백그라운드 코드가 있으므로, 컴포넌트에 대한 작업을 시작할 수 있습니다. 첫 번째로 src>app>app.component.html 파일을 변경할 수 있습니다.

여기에는 아직 존재하지 않는 함수를 위한 코드가 일부 있습니다. 이러한 함수를 이 컴포넌트를 위한 TypeScript 파일에 추가하겠습니다.

<div class="sample-tutorial">
    <gc-spread-sheets [backColor]="spreadBackColor" [hostStyle]="hostStyle" (workbookInitialized)="workbookInit($event)">
        <gc-worksheet [name]="sheetName" [dataSource]="data">
            <gc-column dataField="Name" width=300></gc-column>
            <gc-column dataField="Category" [width]=columnWidth></gc-column>
            <gc-column dataField="Price" [width]=columnWidth formatter="$ #.00"></gc-column>
            <gc-column dataField="Shopping Place" [width]=columnWidth></gc-column>
        </gc-worksheet>
    </gc-spread-sheets>
    <div class="options-container">
        <div class="option-row">
            <div class="inputContainer">            
                <input type="file" id="fileDemo" class="input" (change)="changeFileDemo($event)">
                <br >
                <input type="button" id="loadExcel" value="import" class="button" (click)="loadExcel($event)">
            </div>
            <div class="inputContainer">
                <input id="exportFileName" value="export.xlsx" class="input" (change)="changeExportFileName($event)">
                <input type="button" id="saveExcel" value="export" class="button" (click)="saveExcel($event)">
            </div>
        </div>
        <div class="option-row">
            <div class="group">
                <label>Password:
                    <input type="password" id="password" (change)="changePassword($event)">
                </label>
            </div>
        </div>
    </div>
</div>


TypeScript 파일에 함수를 추가하기 전에, src>app>app.component.css 파일에 스타일을 추가합니다.

.sample-tutorial {
    position: relative;
    height: 100%;
    overflow: hidden;
 }
 
 .sample-spreadsheets {
   width: calc(100% - 280px);
   height: 100%;
   overflow: hidden;
   float: left;
 }
 
 .options-container {
   float: right;
   width: 280px;
   padding: 12px;
   height: 100%;
   box-sizing: border-box;
   background: #fbfbfb;
   overflow: auto;
 }
 
 .sample-options {
   z-index: 1000;
 }
 
 .inputContainer {
   width: 100%;
   height: auto;
   border: 1px solid #eee;
   padding: 6px 12px;
   margin-bottom: 10px;
   box-sizing: border-box;
 }
 
 .input {
   font-size: 14px;
   height: 30px;
   border: 0;
   outline: none;
   background: transparent;
 }
 
 .button {
   height: 30px;
   padding: 6px 12px;
   width: 80px;
   margin-top: 6px;
 }
 
 .group {
   padding: 12px;
 }
 
 .group input {
   padding: 4px 12px;
 }
 body {
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
 }



코드 숨김 설정


이제 src>app>app.component.ts에서 컴포넌트에 사용되는 TypeScript 파일을 설정할 수 있습니다.


import { Component, enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import * as GC from "@grapecity/spread-sheets";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  spread: GC.Spread.Sheets.Workbook;
  spreadBackColor = 'aliceblue';
  sheetName = 'Goods List';
  hostStyle = {
    width: 'calc(100% - 280px)',
    height: '500px',
    overflow: 'hidden',
    float: 'left'
  };
  data = [
    { Name: 'Apple', Category: 'Fruit', Price: 1, 'Shopping Place': 'Wal-Mart' },
    { Name: 'Potato', Category: 'Fruit', Price: 2.01, 'Shopping Place': 'Other' },
    { Name: 'Tomato', Category: 'Vegetable', Price: 3.21, 'Shopping Place': 'Other' },
    { Name: 'Sandwich', Category: 'Food', Price: 2, 'Shopping Place': 'Wal-Mart' },
    { Name: 'Hamburger', Category: 'Food', Price: 2, 'Shopping Place': 'Wal-Mart' },
    { Name: 'Grape', Category: 'Fruit', Price: 4, 'Shopping Place': 'Sun Store' }
  ];
  columnWidth = 100;

  constructor() {
    this.spread = new GC.Spread.Sheets.Workbook();
  }
  workbookInit(args: { spread: GC.Spread.Sheets.Workbook; }){
    this.spread = args.spread;
    let spread = this.spread;
    let sheet = spread.getActiveSheet();
  }
}


이렇게 하면 Angular 앱의 기본 SpreadJS 인스턴스가 설정됩니다.

하지만 우리는 Excel 가져오기 및 내보내기 기능을 추가하여 확실한 Excel 뷰어로 만들고자 합니다.

Angular Excel XLSX 뷰어




Excel 가져오기/내보내기 코드 추가



이제 SpreadJS 인스턴스가 설정되었으므로, 동일한 src>app>app.component.ts 파일에 일부 ExcelIO 코드를 추가할 수 있습니다. ExcelIO 코드에 대한 액세스 권한을 제공합니다. 추가적으로 해당 파일의 상단에 다른 가져오기 행과 함께 사용할 변수를 선언해야 합니다.


...
import * as ExcelIO from "@grapecity/spread-excelio";
declare var saveAs: any;
...


AppComponent 클래스 내에서, 나중에 사용할 추가 변수를 초기화할 수 있습니다.


hostStyle 초기화 후에 이를 추가할 수 있습니다.

hostStyle = {
  ...
}
importExcelFile: any;
exportFileName = "export.xlsx";
password: string = "";


src>index.html 파일에 src>assets>FileSaver.js 파일에 대한 참조를 추가해야 합니다.

<!doctype html>
<html style="height:100%;font-size:14px;" lang="en">
<head>
<meta charset="utf-8">
<title>SpreadSheetsAngularCli</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="./assets/FileSaver.js"></script>
</head>
<body>
<app-root></app-root>
</body>
</html>


다음 단계는 사용자가 가져오기 및 내보내기를 위한 파일을 변경할 때 실행될 함수 및 비밀번호를 AppComponent 클래스의 src>app>app.components.ts 파일에 추가하는 것입니다.

workbookInit(...) {
  ...
}

changeFileDemo(e: any) {
  this.importExcelFile = e.target.files[0];
}
changePassword(e: any) {
  this.password = e.target.value;
}
changeExportFileName(e: any) {
  this.exportFileName = e.target.value;
}

Excel 파일을 로드하기 위한 코드를 SpreadJS에 추가할 수 있습니다. 이 경우, 열 때 비밀번호를 활용합니다.

loadExcel(e: any) {
  let spread = this.spread;
  let excelIo = new ExcelIO.IO();
  let excelFile = this.importExcelFile;
  let password = this.password;
  excelIo.open(excelFile, function (json: any) {
    let workbookObj = json;
    spread.fromJSON(workbookObj);
  }, function (e: any) {
      alert(e.errorMessage);
  }, { password: password });
}



또한 비밀번호를 사용하여 Excel 파일을 저장할 수 있으며, 이 SpreadJS 인스턴스의 경우 초기에 데이터를 로드하므로 includeBindingSource 옵션을 추가해야 합니다.

saveExcel(e: any) {
  let spread = this.spread;
  let excelIo = new ExcelIO.IO();
  let fileName = this.exportFileName;
  let password = this.password;
  if (fileName.substr(-5, 5) !== '.xlsx') {
      fileName += '.xlsx';
  }
  let json = spread.toJSON({includeBindingSource: true});
  // here is excel IO API
  excelIo.save(json, function (blob: any) {
      saveAs(blob, fileName);
  }, function (e: any) {
      // process error
      console.log(e);
  }, { password: password });
}


Angular Excel XLSX 뷰어


SpreadJS를 사용한 Angular 응용 프로그램에서 Excel 뷰어를 만드는 데 필요한 모든 단계가 완료되었습니다!




지금 바로 SpreadJS를 다운로드하여 직접 테스트해보세요!

  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.