Excel에서 Angular 그리드 붙여넣기

    Ignite UI for Angular IgxGrid 클립보드에 복사된 Excel 데이터를 읽을 수 있습니다. 이 섹션에서는 사용자 지정 코드로 이를 수행하는 방법을 보여드리겠습니다.

    Excel에서 Angular 붙여넣기 예제

    이 샘플은 Excel에서 igxGrid Material UI 테이블로 붙여넣기를 구현하는 방법을 보여줍니다. 샘플을 사용하려면 Excel 스프레드시트를 열고 일부 행을 복사한 다음 키보드(Ctrl + V, Shift + Insert, Command + V)를 사용하여 그리드에 붙여넣습니다.

    상단에는 2가지 옵션이 있는 드롭다운 버튼이 있습니다.

    1. "데이터를 새 행으로 붙여넣기" – 이 모드에서는 Excel에서 복사한 모든 데이터가 그리드에 새 행으로 추가됩니다.
    2. "활성 셀부터 붙여넣기" - 이 모드에서는 그리드의 데이터를 덮어씁니다.

    붙여넣기 후의 새 데이터는 기울임꼴로 장식됩니다.

    용법

    당신은 paste-handler 지시문(다음 섹션에서 해당 코드를 찾을 수 있음) igxGrid 그리고 그것을 처리 onDataProcessed 이벤트. 그만큼 onDataProcessed 이벤트에는 배열 형식의 Excel 데이터에 대한 액세스를 제공하는 하나의 매개변수가 있습니다. 참고로 addRecords 그리고 updateRecords 행동 양식.

    <igx-grid #grid1 [data]="data" [width]="'100%'" [height]="'505px'" [autoGenerate]="false" paste-handler (onDataProcessed)="dataPasted($event)" [primaryKey]="'ID'"> <igx-column [field]="'Name'"></igx-column> <igx-column [field]="'Title'"></igx-column> <igx-column [field]="'Phone'"></igx-column> <igx-column [field]="'Country'"></igx-column> </igx-grid>
    public dataPasted(processedData) { if (this.pasteMode === "Paste data as new records") { this.addRecords(processedData); } else { this.updateRecords(processedData); } } public addRecords(processedData: any[]) { const columns = this.grid1.visibleColumns; const pk = this.grid1.primaryKey; const addedData = []; for (const curentDataRow of processedData) { const rowData = {}; for (const col of columns) { rowData[col.field] = curentDataRow[col.visibleIndex]; } // generate PK rowData[pk] = this.grid1.data.length + 1; this.grid1.addRow(rowData); addedData.push(rowData); this.grid1.cdr.detectChanges(); } // scroll to last added row this.grid1.verticalScrollContainer.scrollTo(this.grid1.data.length); this.grid1.verticalScrollContainer.chunkLoad.pipe(take(1)).subscribe(() => { this.clearStyles(); for (const data of addedData) { const row = this.grid1.getRowByKey(data[pk]); if (row) { row.nativeElement.style["font-style"] = "italic"; row.nativeElement.style.color = "gray"; } } }); } public updateRecords(processedData: any[]) { const cell = this.grid1.selectedCells[0]; const pk = this.grid1.primaryKey; if (!cell) { return; } const rowIndex = cell.row.index; // const rowPkValue = cell.row.data[pk]; const cellIndex = cell.column.visibleIndex; const columns = this.grid1.visibleColumns; let index = 0; const updatedRecsPK = []; for (const curentDataRow of processedData) { const rowData = {}; const dataRec = this.grid1.data[rowIndex + index]; const rowPkValue = dataRec ? dataRec[pk] : this.grid1.data.length + 1; rowData[pk] = rowPkValue; for (let j = 0; j < columns.length; j++) { let currentCell; if (j >= cellIndex) { currentCell = curentDataRow.shift(); } const colKey = columns[j].field; rowData[colKey] = currentCell || (!!dataRec ? dataRec[colKey] : null); } if (!dataRec) { // no rec to update, add instead rowData[pk] = rowPkValue; this.grid1.addRow(rowData); continue; } this.grid1.updateRow(rowData, rowPkValue); this.grid1.cdr.detectChanges(); updatedRecsPK.push(rowPkValue); index++; } this.clearStyles(); for (const pkVal of updatedRecsPK) { const row = this.grid1.getRowByKey(pkVal); if (row) { row.nativeElement.style["font-style"] = "italic"; row.nativeElement.style.color = "gray"; } } } protected clearStyles() { for (const row of this.grid1.rowList.toArray()) { row.nativeElement.style["font-style"] = ""; row.nativeElement.style.color = ""; } }

    붙여넣기 처리기 지시문

    이것은 paste-handler 구현입니다. 이 코드는 클립보드에서 붙여넣은 데이터를 수신하는 데 사용되는 DOM textarea 요소를 생성합니다. 데이터가 textarea에 붙여넣어지면 지시문은 이를 배열로 구문 분석한 다음 구문 분석된 데이터를 전달하는 onDataProcessed 맞춤 이벤트를 내보냅니다.

    import { Directive, EventEmitter, HostListener, Output} from "@angular/core"; @Directive({ selector: "[paste-handler]" }) export class PasteHandler { public textArea; @Output() public onDataProcessed = new EventEmitter<any>(); public ngOnInit(): void { const div = document.createElement("div"); const divStyle = div.style; divStyle.position = "fixed"; document.body.appendChild(div); this.textArea = document.createElement("textarea"); const style = this.textArea.style; style.opacity = "0"; style.height = "0px"; style.width = "0px"; style.overflow = "hidden"; div.appendChild(this.textArea); this.textArea.addEventListener("paste", (eventArgs) => { this.onPaste(eventArgs); }); } @HostListener("focusin", ["$event"]) public focusIn(eventArgs) { } @HostListener("keydown", ["$event"]) public ControlV(eventArgs) { const ctrl = eventArgs.ctrlKey; const key = eventArgs.keyCode; // Ctrl-V || Shift-Ins || Cmd-V if ((ctrl || eventArgs.metaKey) && key === 86 || eventArgs.shiftKey && key === 45) { this.textArea.focus(); } } public onPaste(eventArgs) { let data; const clData = "clipboardData"; // get clipboard data - from window.cliboardData for IE or from the original event's arguments. if (window[clData]) { window.event.returnValue = false; data = window[clData].getData("text"); } else { data = eventArgs[clData].getData("text/plain"); } // process the clipboard data const processedData = this.processData(data); this.onDataProcessed.emit(processedData); } public processData(data) { const pasteData = data.split("\n"); for (let i = 0; i < pasteData.length; i++) { pasteData[i] = pasteData[i].split("\t"); // Check if last row is a dummy row if (pasteData[pasteData.length - 1].length === 1 && pasteData[pasteData.length - 1][0] === "") { pasteData.pop(); } // remove empty data if (pasteData.length === 1 && pasteData[0].length === 1 && (pasteData[0][0] === "" || pasteData[0][0] === "\r")) { pasteData.pop(); } } return pasteData; } }

    API 참조

    추가 리소스

    • Excel 내보내기- Excel 내보내기 서비스를 사용하여 IgxGrid에서 Excel로 데이터를 내보냅니다. 또한 IgxGrid에서 선택한 데이터만 내보내는 옵션도 제공합니다. 내보내기 기능은 IgxExcelExporterService 클래스에 캡슐화되어 있으며 데이터는 MS Excel 테이블 형식으로 내보내집니다. 이 형식을 사용하면 필터링, 정렬 등과 같은 기능을 사용할 수 있습니다. 이렇게 하려면 IgxExcelExporterService의 내보내기 메소드를 호출하고 IgxGrid 구성 요소를 첫 번째 인수로 전달해야 합니다.
    우리 커뮤니티는 활동적이며 항상 새로운 아이디어를 환영합니다.