Skip to content

Commit

Permalink
feat(vue): dynamically create grid from imported CSV data (#1773)
Browse files Browse the repository at this point in the history
* feat(vue): dynamically create grid from imported CSV data
  • Loading branch information
ghiscoding authored Dec 12, 2024
1 parent 2c32450 commit d67d339
Show file tree
Hide file tree
Showing 5 changed files with 251 additions and 1 deletion.
160 changes: 160 additions & 0 deletions demos/vue/src/components/Example43.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
<script setup lang="ts">
import { ExcelExportService } from '@slickgrid-universal/excel-export';
import { type Column, type GridOption, SlickgridVue, toCamelCase } from 'slickgrid-vue';
import { ref } from 'vue';
const gridCreated = ref(false);
const gridOptions = ref<GridOption>();
const columnDefinitions = ref<Column[]>([]);
const dataset = ref<any[]>([]);
const templateUrl = ref(new URL('./data/users.csv', import.meta.url).href);
const uploadFileRef = ref('');
const showSubTitle = ref(true);
function destroyGrid() {
gridCreated.value = false;
}
function handleFileImport(event: any) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (e: any) => {
const content = e.target.result;
dynamicallyCreateGrid(content);
};
reader.readAsText(file);
}
}
function handleDefaultCsv() {
const staticDataCsv = `First Name,Last Name,Age,Type\nBob,Smith,33,Teacher\nJohn,Doe,20,Student\nJane,Doe,21,Student`;
dynamicallyCreateGrid(staticDataCsv);
uploadFileRef.value = '';
}
function dynamicallyCreateGrid(csvContent: string) {
// dispose of any previous grid before creating a new one
gridCreated.value = false;
const dataRows = csvContent?.split('\n');
const colDefs: Column[] = [];
const outputData: any[] = [];
// create column definitions
dataRows.forEach((dataRow, rowIndex) => {
const cellValues = dataRow.split(',');
const dataEntryObj: any = {};
if (rowIndex === 0) {
// the 1st row is considered to be the header titles, we can create the column definitions from it
for (const cellVal of cellValues) {
const camelFieldName = toCamelCase(cellVal);
colDefs.push({
id: camelFieldName,
name: cellVal,
field: camelFieldName,
filterable: true,
sortable: true,
});
}
} else {
// at this point all column defs were created and we can loop through them and
// we can now start adding data as an object and then simply push it to the dataset array
cellValues.forEach((cellVal, colIndex) => {
dataEntryObj[colDefs[colIndex].id] = cellVal;
});
// a unique "id" must be provided, if not found then use the row index and push it to the dataset
if ('id' in dataEntryObj) {
outputData.push(dataEntryObj);
} else {
outputData.push({ ...dataEntryObj, id: rowIndex });
}
}
});
gridOptions.value = {
gridHeight: 300,
gridWidth: 800,
enableFiltering: true,
enableExcelExport: true,
externalResources: [new ExcelExportService()],
headerRowHeight: 35,
rowHeight: 33,
};
dataset.value = outputData;
columnDefinitions.value = colDefs;
gridCreated.value = true;
}
function toggleSubTitle() {
showSubTitle.value = !showSubTitle.value;
const action = showSubTitle.value ? 'remove' : 'add';
document.querySelector('.subtitle')?.classList[action]('hidden');
}
</script>

<template>
<h2>
Example 43: Dynamically Create Grid from CSV / Excel import
<span class="float-end">
<a
style="font-size: 18px"
target="_blank"
href="https://github.com/ghiscoding/slickgrid-universal/blob/master/demos/vue/src/components/Example43.vue"
>
<span class="mdi mdi-link-variant"></span> code
</a>
</span>
<button
class="ms-2 btn btn-outline-secondary btn-sm btn-icon"
type="button"
data-test="toggle-subtitle"
@click="toggleSubTitle()"
>
<span class="mdi mdi-information-outline" title="Toggle example sub-title details"></span>
</button>
</h2>

<div class="subtitle">
Allow creating a grid dynamically by importing an external CSV or Excel file. This script demo will read the CSV file and will
consider the first row as the column header and create the column definitions accordingly, while the next few rows will be
considered the dataset. Note that this example is demoing a CSV file import but in your application you could easily implemnt
an Excel file uploading.
</div>

<div>A default CSV file can be download <a id="template-dl" :href="templateUrl">here</a>.</div>

<div class="d-flex mt-5 align-items-end">
<div class="file-upload">
<label for="formFile" class="form-label">Choose a CSV file…</label>
<input class="form-control" type="file" data-test="file-upload-input" :value="uploadFileRef" @change="handleFileImport" />
</div>
<span class="mx-3">or</span>
<div>
<button id="uploadBtn" data-test="static-data-btn" class="btn btn-outline-secondary" @click="handleDefaultCsv">
Use default CSV data
</button>
<button class="btn btn-outline-secondary ms-1" @click="destroyGrid()">Destroy Grid</button>
</div>
</div>

<hr />

<slickgrid-vue
v-if="gridCreated"
v-model:options="gridOptions"
v-model:columns="columnDefinitions as Column[]"
v-model:data="dataset"
grid-id="grid43"
>
</slickgrid-vue>
</template>

<style lang="scss">
.file-upload {
max-width: 300px;
}
</style>
5 changes: 5 additions & 0 deletions demos/vue/src/components/data/users.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
First Name,Last Name,Age,User Type
John,Doe,20,Student
Bob,Smith,33,Assistant Teacher
Jane,Doe,21,Student
Robert,Ken,42,Teacher
2 changes: 2 additions & 0 deletions demos/vue/src/router/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import Example39 from '../components/Example39.vue';
import Example40 from '../components/Example40.vue';
import Example41 from '../components/Example41.vue';
import Example42 from '../components/Example42.vue';
import Example43 from '../components/Example43.vue';
import Home from '../Home.vue';

export const routes: RouteRecordRaw[] = [
Expand Down Expand Up @@ -88,6 +89,7 @@ export const routes: RouteRecordRaw[] = [
{ path: '/example40', name: '40- Infinite Scroll from JSON data', component: Example40 },
{ path: '/example41', name: '41- Drag & Drop', component: Example41 },
{ path: '/example42', name: '42- Custom Pagination', component: Example42 },
{ path: '/example43', name: '43- Create Grid from CSV', component: Example43 },
];

export const router = createRouter({
Expand Down
83 changes: 83 additions & 0 deletions demos/vue/test/cypress/e2e/example43.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
describe('Example 43 - Dynamically Create Grid from CSV / Excel import', () => {
const defaultCsvTitles = ['First Name', 'Last Name', 'Age', 'Type'];
const GRID_ROW_HEIGHT = 33;

it('should display Example title', () => {
cy.visit(`${Cypress.config('baseUrl')}/example43`);
cy.get('h2').should('contain', 'Example 43: Dynamically Create Grid from CSV / Excel import');
});

it('should load default CSV file and expect default column titles', () => {
cy.get('[data-test="static-data-btn"]').click();

cy.get('.slick-header-columns')
.children()
.each(($child, index) => expect($child.text()).to.eq(defaultCsvTitles[index]));
});

it('should expect default data in the grid', () => {
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Bob');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(1)`).should('contain', 'Smith');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(2)`).should('contain', '33');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).should('contain', 'Teacher');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(0)`).should('contain', 'John');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(2)`).should('contain', '20');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(0)`).should('contain', 'Jane');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(2)`).should('contain', '21');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');
});

it('should sort by "Age" and expect it to be sorted in ascending order', () => {
cy.get('.slick-header-columns .slick-header-column:nth(2)').click();

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'John');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(2)`).should('contain', '20');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(0)`).should('contain', 'Jane');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(2)`).should('contain', '21');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(0)`).should('contain', 'Bob');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(1)`).should('contain', 'Smith');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(2)`).should('contain', '33');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(3)`).should('contain', 'Teacher');
});

it('should click again the "Age" column and expect it to be sorted in descending order', () => {
cy.get('.slick-header-columns .slick-header-column:nth(2)').click();

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Bob');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(1)`).should('contain', 'Smith');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(2)`).should('contain', '33');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).should('contain', 'Teacher');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(0)`).should('contain', 'Jane');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(2)`).should('contain', '21');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 1}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(0)`).should('contain', 'John');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(1)`).should('contain', 'Doe');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(2)`).should('contain', '20');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 2}px;"] > .slick-cell:nth(3)`).should('contain', 'Student');
});

it('should filter Smith as "Last Name" and expect only 1 row in the grid', () => {
cy.get('.slick-headerrow .slick-headerrow-column:nth(1) input').type('Smith');

cy.get('.slick-row').should('have.length', 1);

cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(0)`).should('contain', 'Bob');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(1)`).should('contain', 'Smith');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(2)`).should('contain', '33');
cy.get(`[style="top: ${GRID_ROW_HEIGHT * 0}px;"] > .slick-cell:nth(3)`).should('contain', 'Teacher');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default class Example31 {
// create column definitions
dataRows.forEach((dataRow, rowIndex) => {
const cellValues = dataRow.split(',');
const dataEntryObj = {};
const dataEntryObj: any = {};

if (rowIndex === 0) {
// the 1st row is considered to be the header titles, we can create the column definitions from it
Expand Down

0 comments on commit d67d339

Please sign in to comment.