Javascript/Sencha

Sencha grid csv 데이터 로딩

바리새인 2025. 1. 15. 22:57
tbar: [
    {
        text: 'Load CSV',
        handler: function() {
            // Trigger a file input dialog to select a CSV file
            const fileInput = document.createElement('input');
            fileInput.type = 'file';
            fileInput.accept = '.csv';
            fileInput.onchange = function(event) {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const csvContent = e.target.result;
                        const rows = csvContent.split('\n');

                        // Assume the first row contains headers; ignore it
                        const data = rows.slice(1).map(row => {
                            const values = row.split(',');
                            return {
                                name: values[0]?.trim(),
                                email: values[1]?.trim(),
                                phone: values[2]?.trim()
                            };
                        });

                        // Load parsed data into the store
                        const store = Ext.ComponentQuery.query('grid')[0].getStore();
                        store.loadData(data);
                    };
                    reader.readAsText(file);
                }
            };
            fileInput.click();
        }
    }
]

csv의 헤더를 제거하고 업로드: slice(1)

// Assume the first row contains headers; ignore it
const data = rows.slice(1).map(row => {
    const values = row.split(',');
    return {
        name: values[0]?.trim(),
        email: values[1]?.trim(),
        phone: values[2]?.trim()
    };
});