0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Angular】【ExcelJS】ライブラリを使用してExcelファイルを出力するよ

Last updated at Posted at 2023-09-15

AangularでExcelJSを使う

データベースのデータをテキストボックスに入力した値でWHEREして取得し、ExcelJSを使用してExcelファイルに出力…

というような内容を行ったので、備忘録として。
(AngularでExcelJS使ってる日本語記事が少なかったので…)

筆者について Angular歴は2カ月

学生時代にHTML,css,JavaScriptについては勉強
TypeScriptではReactの業務経験は有

準備

Angular プロジェクトにexceljs ライブラリをインストール

npm install exceljs --save

コンポーネントを作成

ng g c exceljs

コンポーネントでexceljsをimport

exceljs.component.ts
import * as ExcelJS from 'exceljs';

実装

templateにボタンを設置

exceljs.component.html
<div class="row" style="width: 100%;">
    <ng-container>
        <div>
            <button  style="width: 130px; margin-bottom: 80px;" (click)="exportExcel()">
                    Excel出力ボタン
            </button>
        </div>
    </ng-container>
</div>

exceljs.component.ts
import * as ExcelJS from 'exceljs';

@Component({
  selector: 'exceljs',
  templateUrl: './exceljs.component.html',
  styleUrls: ['./exceljs.component.css']
})
export class ArrangeListExportComponent implements OnInit,OnDestroy{
    constructor(){}

    async exportExcel(){

        // 新しいワークブックを作成
        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet('シート名');
        
        // スタイル定義
        const style = {
	      font: {
	        name: 'MS Pゴシック',
	        size: 9,
	        bold: false,
	      },
	      alignment: {
	        vertical: 'middle',
	      } as Alignment,
	    } as Style;

        // AからZの列の1000行目までにスタイル設定
	    for (let i = 65; i <= 90; i++) {
		    const character = String.fromCharCode(i);
		    for (let j = 1; j <= 1000; j++) {
		        const cellAddress = `${character}${j}`;
		        const cell = worksheet.getCell(cellAddress);
		        cell.style = style;
		    }
		}
		
		// 列ごとに幅を指定できる
		 worksheet.getColumn('A').width = 4.00;
		
		// 結合したいセルの始点と終点を指定
		const mergeCellRanges = [
		    { start: 'A1', end: 'M1' },
		    { start: 'A2', end: 'B2' },
		]
		for (const { start, end } of mergeCellRanges) {
		    this.mergeCells(worksheet, start, end);
		}
		
		// セルに出力する値をセット
		this.writeToCell(worksheet, 'A1', "セルに値をセット");
		
		// Excelファイルをダウンロード
    	this.downloadFile(buffer, 'ファイル名.xlsx');

}

	private downloadFile(data: ArrayBuffer, filename: string) {
	    const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
	    const url = window.URL.createObjectURL(blob);

	    const a = document.createElement('a');
	    a.href = url;
	    a.download = filename;
	    a.click();

	    window.URL.revokeObjectURL(url);
	}

	// セル結合を行うメソッド
	mergeCells(worksheet, startCell, endCell) {
		worksheet.mergeCells(startCell, endCell);
	}
	
	// Excelファイルに書き込む値とセルを指定するメソッド
  	writeToCell(worksheet, cellAddress, value) {
    	worksheet.getCell(cellAddress).value = value;
  	}

出力結果

image.png

A1~M1 A2とB2 が結合されており、
フォントがMS Pゴシック、サイズが9
シート名が「シート名」となっており、ファイル名が「ファイル名.xlsx」
であることを確認

Excel出力処理について
記事が長くなってしまうのでcomponentファイルに記述しましたが、実装する際はServiceファイルを作成してそちらに定義した方が良いと思われます。

あとがき

Angularはいいぞ

andmore...

他にもこんな記事書いてます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?