Skip to content

Instantly share code, notes, and snippets.

@kuc-arc-f
Created January 14, 2022 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuc-arc-f/b73e4ac65843b4208007fadb1a744e18 to your computer and use it in GitHub Desktop.
Save kuc-arc-f/b73e4ac65843b4208007fadb1a744e18 to your computer and use it in GitHub Desktop.
Excel(exceljs) sample, react 17
/* jsPdf , japan lang sample */
import React from 'react'
const ExcelJS = require('exceljs');
interface IProps {
history:string[],
}
//
class Test extends React.Component<IProps> {
constructor(props: any) {
super(props);
this.state = {data: ''}
}
componentDidMount(){
}
async clickButtonAsync(e: any){
e.preventDefault();
// Workbookの作成
const workbook = new ExcelJS.Workbook();
// Workbookに新しいWorksheetを追加
workbook.addWorksheet('My Sheet');
// ↑で追加したWorksheetを参照し変数に代入
const worksheet = workbook.getWorksheet('My Sheet');
// 列を定義
worksheet.columns = [
{ header: 'ID', key: 'id' },
{ header: '名称', key: 'name' },
{ header: '価格', key: 'price' },
];
// 行を定義
worksheet.addRow({id: 1001, name: 'みかん', price: 170});
worksheet.addRow({id: 1002, name: 'バナナ', price: 200});
worksheet.addRow({id: 1003, name: 'りんご', price: 260});
worksheet.addRow({id: 1004, name: 'トマト', price: 190});
// UInt8Arrayを生成
const uint8Array = await workbook.xlsx.writeBuffer();
// Blob
const blob = new Blob([uint8Array], {type: 'application/octet-binary'});
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `sample.xlsx`;
a.click();
// ダウンロード後は不要なのでaタグを除去
a.remove()
}
render(){
return(
<div >
<h1>xls2</h1>
<hr />
<button onClick={(e) => this.clickButtonAsync(e)}>Test</button>
<hr />
</div>
)
}
}
export default Test;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment