Skip to content

Instantly share code, notes, and snippets.

@gotexis
Last active June 20, 2023 08:57
Show Gist options
  • Save gotexis/34ed4ba97317303acb233e4cbb035725 to your computer and use it in GitHub Desktop.
Save gotexis/34ed4ba97317303acb233e4cbb035725 to your computer and use it in GitHub Desktop.
Pasting excel / google sheet into editable table with mui-datagrid-pro
{
field: "fieldname",
width: 130,
editable: true,
renderEditCell: (params) => renderCell({ ...params, onPaste }),
}
const onPaste: PasteHandler = (targetColumn) => (targetRowId) => (e) => {
const pastedData = e.clipboardData?.getData("text");
if (!pastedData) return;
const rowsPasted = pastedData.split("\n");
const pastedMatrix = rowsPasted.map((row) => row.split("\t"));
// just a normal paste
if (pastedMatrix.length <= 1) return;
// suppress the default paste behavior
e.preventDefault();
// find the index of the column where the paste started
const targetColumnIndex = columns.findIndex((x) => x.field === targetColumn);
// e.g.
// [
// ["a", "b", "c"],
// ["d", "e", "f"],
// ["g", "h", "i"]
// ]
// get the affected rows, considering the table may have a sort
const displayedRowIds = apiRef.current!.getSortedRowIds(); // e.g. [2,3,5,6,1,4]
// calculate which rows are affected.
const startRowIndex = getValues("Details").findIndex((i) => i.id === targetRowId);
const endRowIndex = startRowIndex + rowsPasted.length;
const affectedRowSlice = displayedRowIds.slice(startRowIndex, endRowIndex);
const updated = getValues("Details").map((row) => {
if (affectedRowSlice.includes(row.id)) {
const rowIndex = affectedRowSlice.indexOf(row.id);
const cells = pastedMatrix[rowIndex];
return cells.reduce((acc, cell, index) => {
const field = columns[targetColumnIndex + index]?.field as keyof DetailInput;
if (field) {
acc[field] = cell;
}
return acc;
}, row as Record<keyof DetailInput, string | null | undefined>);
}
return row;
});
// @ts-ignore
setValue("Details", updated);
apiRef.current?.setEditCellValue({
id: targetRowId,
field: targetColumn,
value: pastedMatrix[0][0]
});
setForceUpdateKey((prevKey) => prevKey + 1);
};
@sebastianvoss
Copy link

Thanks for sharing this. Is PasteHandler from https://github.com/google/closure-library/?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment