프론트엔드 (Front-End)/VUE.js

Excel 구현 (.xlsx)

xxvigrufv 2022. 6. 22. 17:07
반응형

Excel 구현 (.xlsx)

.xlsx 확장자로 엑셀파일을 뽑아내기 위해 Excel을 구현해보았다. 

엑셀 확장자 ".xlsx"와 ".xls"의 차이점

  1) ".xlsx"는 Excel2007 이후 형식으로 문서를 만든경우 생성되는 확장자

  2) ".xls"는 Excel2003 이전 형식으로 문서를 만든경우 생성되는 확장자
  
Microsoft Word의 확장자 ".docx"와 ".doc" 
Microsoft PowerPoint의 ".pptx"와 ".ppt"



import * as Xlsx from 'xlsx';

export default {
	methods: {
		downloadTableTemplate(headers, list) {
			return `
        <html xmlns:x="urn:schemas-microsoft-com:office:excel">
          <head>
            <meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">
            <xml>
              <x:ExcelWorkbook>
                <x:ExcelWorksheets>
                  <x:ExcelWorksheet>
                    <x:Name>SHIELD@Home</x:Name>
                    <x:WorksheetOptions>
                      <x:Panes></x:Panes>
                    </x:WorksheetOptions>
                  </x:ExcelWorksheet>
                </x:ExcelWorksheets>
              </x:ExcelWorkbook>
            </xml>
          </head>
          <body>
            <table>
              <thead>
                <tr>
                  ${(() => {
										let str = '';
										// eslint-disable-next-line no-unused-vars
										for (let item in headers)
											if (headers[item])
												str += '<th>' + headers[item].title + '</th>';
										return str;
									})()}
                </tr>
              </thead>
              <tbody>
                ${(() => {
									let str = '';
									list.forEach(items => {
										str += '<tr>';
										items.forEach(item => {
											if (item) str += '<td>' + item.text + '</td>';
										});
										str += '</tr>';
									});
									return str;
								})()}
              </tbody>
          </table>
        </body>
      </html>
      `;
		},

		makeExcelFile5(list, fileName) {
			//생성 날짜 시간
			let today = new Date();
			let year = today.getFullYear(); // 년도
			let month = today.getMonth() + 1; // 월
			let date = today.getDate(); // 날짜
			const creationDate = year + '_' + month + '_' + date;

			//Xlsx 워크북 만들기
			const workBook = Xlsx.utils.book_new();
			const workSheet = Xlsx.utils.json_to_sheet(list);

			//Excel 파일 컬럼 너비 설정
			workSheet['!cols'] = [
				{ wch: 25 },
				{ wch: 25 },
				{ wch: 25 },
				{ wch: 25 },
				{ wch: 25 },
				{ wch: 25 },
				{ wch: 25 },
			];

			Xlsx.utils.book_append_sheet(workBook, workSheet, 'SHIELD@Home');

			//파일명 구조 및 파일형식
			Xlsx.writeFile(
				workBook,
				'SHIELD@Home_' + fileName + '_' + creationDate + '.xlsx',
			);
		},
	},
};


               
npm install xlsx를 사용하여 xlsx 설치한다.

 npm install xlsx

 


 
 
설치한 xlsx 모듈을 가져온다. * 'xlsx'에서 XLSX로 가져오기;

반응형