Hi, I am new to using the component library. I would like to export checkbox selected rows to excel through the Datagrid component.
Here is the code that I am using,
import '@progress/kendo-theme-bootstrap/dist/all.css';
import {
Grid,
getSelectedState,
GridToolbar,
GridColumn,
} from "@progress/kendo-react-grid";
import { ExcelExport, ExcelExportColumn } from '@progress/kendo-react-excel-export';
import { getter } from "@progress/kendo-react-common";
import products from "./products.json";
import { useCallback, useRef, useState } from 'react';
const DATA_ITEM_KEY = "ProductID";
const SELECTED_FIELD = "selected";
const idGetter = getter(DATA_ITEM_KEY);
const EDIT_FIELD = "inEdit";
const App = () => {
const [dataState, setDataState] = useState(
products.map((dataItem) =>
Object.assign(
{
selected: false,
},
dataItem
)
)
);
const [selectedState, setSelectedState] = useState({});
const onSelectionChange = useCallback(
(event) => {
const newSelectedState = getSelectedState({
event,
selectedState: selectedState,
dataItemKey: DATA_ITEM_KEY,
});
console.log(event.dataItems)
setSelectedState(newSelectedState);
},
[selectedState]
);
const _grid = useRef();
const _export = useRef(null);
const excelExport = () => {
if (_export.current !== null) {
_export.current.save(products, _grid.current.columns);
}
};
const onHeaderSelectionChange = useCallback((event) => {
const checkboxElement = event.syntheticEvent.target;
const checked = checkboxElement.checked;
const newSelectedState = {};
event.dataItems.forEach((item) => {
newSelectedState[idGetter(item)] = checked;
});
setSelectedState(newSelectedState);
}, []);
console.log(selectedState)
// console.log(_grid)
// console.log(_export)
return (
<div>
<ExcelExport ref={_export}>
<Grid
data={dataState.map((item) => ({
...item,
[SELECTED_FIELD]: selectedState[idGetter(item)],
}))}
style={{
height: "400px",
}}
dataItemKey={DATA_ITEM_KEY}
selectedField={SELECTED_FIELD}
selectable={{
enabled: true,
drag: false,
cell: false,
mode: "multiple",
}}
onSelectionChange={onSelectionChange}
onHeaderSelectionChange={onHeaderSelectionChange}
ref={_grid}
>
<GridToolbar>
<button
title="Export Excel"
className="k-button k-button-md k-rounded-md k-button-solid k-button-solid-primary"
onClick={excelExport}
>
Export to Excel
</button>
</GridToolbar>
<GridColumn
field={SELECTED_FIELD}
width="50px"
headerSelectionValue={
dataState.findIndex((item) => !selectedState[idGetter(item)]) === -1
}
/>
<GridColumn field="ProductName" title="Product Name" width="300px" />
<GridColumn field="UnitsInStock" title="Units In Stock" />
<GridColumn field="UnitsOnOrder" title="Units On Order" />
<GridColumn field="ReorderLevel" title="Reorder Level" />
</Grid>
</ExcelExport>
</div>
);
};
export default App
@stefan can you help?