Javascript/Sencha

Sencha grid의 내용 csv로 저장하기

바리새인 2025. 1. 15. 22:53
tbar: [
    {
        text: 'Export to CSV',
        handler: function() {
            const grid = this.up('grid'); // Get reference to the grid
            const store = grid.getStore(); // Get the grid's store

            // Filter columns to exclude those with dataIndex '_$_'
            const columns = grid.getColumns().filter(column => column.dataIndex !== '_$_');

            // Extract column headers
            const headers = columns.map(column => column.text).join(',');

            // Extract store data
            const rows = [];
            store.each(record => {
                const row = columns.map(column => record.get(column.dataIndex));
                rows.push(row.join(','));
            });

            // Combine headers and rows
            const csvContent = [headers, ...rows].join('\n');

            // Add UTF-8 BOM for Hangul support
            const bom = '\uFEFF';
            const csvWithBom = bom + csvContent;

            // Trigger download
            const blob = new Blob([csvWithBom], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = 'grid_data.csv'; // Set the download filename
            link.click();
        }
    }
]

한글 깨지는 문제 해결

// Add UTF-8 BOM for Hangul support
const bom = '\uFEFF';
const csvWithBom = bom + csvContent;

 row의 상태값 컬럼 제거하기

// Filter columns to exclude those with dataIndex '_$_'
const columns = grid.getColumns().filter(column => column.dataIndex !== '_$_');