Skip to content

Commit

Permalink
Convert Excel and ODS files to CSV before upload in onSubmit function
Browse files Browse the repository at this point in the history
Signed-off-by: shevijacobson <[email protected]>
  • Loading branch information
Shevijacobson committed Nov 3, 2024
1 parent c8db633 commit 9114f1e
Show file tree
Hide file tree
Showing 3 changed files with 143 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState } from "react";
import axios, { AxiosResponse } from "axios";
import { useTranslation } from "react-i18next";
import * as XLSX from "xlsx";

import {
ActionGroup,
Expand Down Expand Up @@ -39,13 +40,35 @@ export const ImportApplicationsForm: React.FC<ImportApplicationsFormProps> = ({
setIsFileRejected(true);
};

const onSubmit = () => {
const onSubmit = async () => {
if (!file) {
return;
}

let fileToUpload = file;
const fileExtension = file.name.split(".").pop()?.toLowerCase() || "";

if (["xls", "xlsx", "ods"].includes(fileExtension)) {
const data = await file.arrayBuffer();
const workbook = XLSX.read(data, { type: "array" });

const csvData = XLSX.utils.sheet_to_csv(
workbook.Sheets[workbook.SheetNames[0]]
);
const blob = new Blob([csvData], { type: "text/csv" });

fileToUpload = new File(
[blob],
file.name.replace(/\.(xls|xlsx|ods)$/, ".csv"),
{
type: "text/csv",
}
);
}

const formData = new FormData();
formData.set("file", file);
formData.set("fileName", file.name);
formData.set("file", fileToUpload);
formData.set("fileName", fileToUpload.name);
formData.set(
"createEntities",
isCreateEntitiesChecked === true ? "true" : "false"
Expand Down
113 changes: 113 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,9 @@
"webpack-dev-server": {
"express": "$express"
}
},
"dependencies": {
"@types/xlsx": "^0.0.35",
"xlsx": "^0.18.5"
}
}

0 comments on commit 9114f1e

Please sign in to comment.