XLSX- css and xlsx-mail

This commit is contained in:
Harshitha Shetty
2025-01-24 00:27:39 +05:30
parent e109559d7a
commit 2841638ba5
5 changed files with 475 additions and 265 deletions

View File

@@ -1,197 +1,7 @@
// import React, { useState, useEffect } from "react";
// import axios from "axios";
// const ConsolidatedTable = () => {
// const [data, setData] = useState([]);
// const [loading, setLoading] = useState(true);
// useEffect(() => {
// const fetchData = async () => {
// try {
// const response = await axios.get("http://localhost:8080/api/table/consolidated-table");
// setData(response.data);
// setLoading(false);
// } catch (error) {
// console.error("Error fetching table data:", error);
// setLoading(false);
// }
// };
// fetchData();
// }, []);
// if (loading) {
// return <div>Loading...</div>;
// }
// return (
// <div>
// <h1>Consolidated Table</h1>
// <table border="1" style={{ width: "100%", textAlign: "left" }}>
// <thead>
// <tr>
// <th>Semester</th>
// <th>Course Code</th>
// <th>Course Name</th>
// <th>Exam Type</th>
// <th>Year</th>
// <th>Marks</th>
// <th>Name</th>
// <th>Affiliation/College</th>
// <th>Highest Qualification</th>
// <th>Career Experience</th>
// <th>Oral/Practical</th>
// <th>Assessment</th>
// <th>Reassessment</th>
// <th>Paper Setting</th>
// <th>Moderation</th>
// <th>PwD Paper Setting</th>
// </tr>
// </thead>
// <tbody>
// {data.map((row, index) => (
// <tr key={index}>
// <td>{row.semester}</td>
// <td>{row.courseCode}</td>
// <td>{row.courseName}</td>
// <td>{row.examType}</td>
// <td>{row.year}</td>
// <td>{row.marks}</td>
// <td>{row.Name}</td>
// <td>{row.affiliation}</td>
// <td>{row.qualification}</td>
// <td>{row.experience}</td>
// <td>{row.oralPractical}</td>
// <td>{row.assessment}</td>
// <td>{row.reassessment}</td>
// <td>{row.paperSetting}</td>
// <td>{row.moderation}</td>
// <td>{row.pwdPaperSetting}</td>
// </tr>
// ))}
// </tbody>
// </table>
// </div>
// );
// };
// export default ConsolidatedTable;
// import React, { useState, useEffect } from "react";
// import axios from "axios";
// import { CSVLink } from "react-csv";
// const ConsolidatedTable = () => {
// const [data, setData] = useState([]);
// const [loading, setLoading] = useState(true);
// useEffect(() => {
// const fetchData = async () => {
// try {
// const response = await axios.get("http://localhost:8080/api/table/consolidated-table");
// setData(response.data);
// setLoading(false);
// } catch (error) {
// console.error("Error fetching table data:", error);
// setLoading(false);
// }
// };
// fetchData();
// }, []);
// if (loading) {
// return <div>Loading...</div>;
// }
// // Extract unique faculty names
// const uniqueTeachers = [...new Set(data.map((row) => row.Name))];
// return (
// <div>
// <h1>Faculty Tables with Download Option</h1>
// {uniqueTeachers.map((teacher, index) => {
// // Filter rows for the current teacher
// const teacherData = data.filter((row) => row.Name === teacher);
// return (
// <div key={index} style={{ marginBottom: "20px" }}>
// <h2>{teacher}'s Table</h2>
// <table border="1" style={{ width: "100%", textAlign: "left", marginBottom: "10px" }}>
// <thead>
// <tr>
// <th>Semester</th>
// <th>Course Code</th>
// <th>Course Name</th>
// <th>Exam Type</th>
// <th>Year</th>
// <th>Marks</th>
// <th>Name</th>
// <th>Affiliation/College</th>
// <th>Highest Qualification</th>
// <th>Career Experience</th>
// <th>Oral/Practical</th>
// <th>Assessment</th>
// <th>Reassessment</th>
// <th>Paper Setting</th>
// <th>Moderation</th>
// <th>PwD Paper Setting</th>
// </tr>
// </thead>
// <tbody>
// {teacherData.map((row, idx) => (
// <tr key={idx}>
// <td>{row.semester}</td>
// <td>{row.courseCode}</td>
// <td>{row.courseName}</td>
// <td>{row.examType}</td>
// <td>{row.year}</td>
// <td>{row.marks}</td>
// <td>{row.Name}</td>
// <td>{row.affiliation}</td>
// <td>{row.qualification}</td>
// <td>{row.experience}</td>
// <td>{row.oralPractical}</td>
// <td>{row.assessment}</td>
// <td>{row.reassessment}</td>
// <td>{row.paperSetting}</td>
// <td>{row.moderation}</td>
// <td>{row.pwdPaperSetting}</td>
// </tr>
// ))}
// </tbody>
// </table>
// {/* CSV Download Button */}
// <CSVLink
// data={teacherData}
// filename={`${teacher.replace(/\s+/g, "_")}_table.csv`}
// className="btn btn-primary"
// style={{
// padding: "10px 15px",
// backgroundColor: "#007bff",
// color: "white",
// textDecoration: "none",
// borderRadius: "5px",
// }}
// >
// Download CSV
// </CSVLink>
// </div>
// );
// })}
// </div>
// );
// };
// export default ConsolidatedTable;
import React, { useState, useEffect, useRef } from "react";
import React, { useState, useEffect } from "react";
import axios from "axios";
import { CSVLink } from "react-csv";
import * as XLSX from "xlsx-js-style";
import { sendEmail } from "../api";
const ConsolidatedTable = () => {
const [data, setData] = useState([]);
@@ -236,7 +46,6 @@ const ConsolidatedTable = () => {
[],
];
// Add table headers
const tableHeaders = [
[
"Sr No",
@@ -261,7 +70,6 @@ const ConsolidatedTable = () => {
],
];
// Add table data
const dataRows = teacherData.map((row, index) => [
index + 1,
row.semester,
@@ -284,7 +92,6 @@ const ConsolidatedTable = () => {
row.pwdPaperSetting,
]);
// Combine all rows
const sheetData = [...headerInfo, ...tableHeaders, ...dataRows];
const worksheet = XLSX.utils.aoa_to_sheet(sheetData);
@@ -299,12 +106,12 @@ const ConsolidatedTable = () => {
// Define styles
const boldStyle = {
font: { bold: true, name: "Times New Roman", sz: 12 },
font: { bold: true, name: "Times New Roman", sz: 14 },
alignment: { horizontal: "center", vertical: "center" },
};
const redStyle = {
font: { color: { rgb: "FF0000" }, name: "Times New Roman", sz: 12 },
font: { bold: true, color: { rgb: "FF0000" }, name: "Times New Roman", sz: 14 },
alignment: { horizontal: "center", vertical: "center" },
};
@@ -312,7 +119,7 @@ const ConsolidatedTable = () => {
font: { name: "Times New Roman", sz: 12 },
};
// Apply styles to header
// Apply styles to headers
const headerRanges = [
{ row: 0, style: boldStyle },
{ row: 1, style: boldStyle },
@@ -329,6 +136,29 @@ const ConsolidatedTable = () => {
}
});
// Set column widths for better readability
worksheet["!cols"] = [
{ wch: 10 }, // Sr No
{ wch: 12 }, // Semester
{ wch: 15 }, // Course Code
{ wch: 25 }, // Course Name
{ wch: 15 }, // Exam Type
{ wch: 10 }, // Year
{ wch: 10 }, // Marks
{ wch: 15 }, // Surname
{ wch: 15 }, // First Name
{ wch: 15 }, // Middle Name
{ wch: 20 }, // Affiliation
{ wch: 20 }, // Qualification
{ wch: 15 }, // Career Experience
{ wch: 15 }, // Oral/Practical
{ wch: 15 }, // Assessment
{ wch: 15 }, // Reassessment
{ wch: 15 }, // Paper Setting
{ wch: 15 }, // Moderation
{ wch: 15 }, // PwD Paper Setting
];
// Apply normal font style to all cells
Object.keys(worksheet).forEach((key) => {
if (worksheet[key] && key[0] !== "!") {
@@ -349,45 +179,97 @@ const ConsolidatedTable = () => {
};
const handleSendEmail = async (teacher, teacherData) => {
const csvHeaders = Object.keys(teacherData[0]);
const csvRows = teacherData.map((row) =>
csvHeaders
.map(
(header) => `"${row[header]?.toString().replace(/"/g, '""') || ""}"`
)
.join(",")
);
const csvContent = [csvHeaders.join(","), ...csvRows].join("\n");
const fileName = `${teacher.replace(/\s+/g, "_")}_table.csv`;
const workbook = XLSX.utils.book_new();
const headerInfo = [
["Somaiya Vidyavihar University"],
["K. J. SOMAIYA COLLEGE OF ENGINEERING"],
[
"Appointment of Internal Examiners for Paper Setting / OR/PR/Assessment/Reassessment",
],
["Class: B Tech/M Tech/Honour/Minor"],
["Department - Computer Engineering"],
[],
];
const tableHeaders = [
[
"Sr No",
"Semester",
"Course Code",
"Course Name",
"Exam Type",
"Year",
"Marks",
"Surname",
"First Name",
"Middle Name",
"Affiliation/College",
"Highest Qualification",
"Career Experience",
"Oral/Practical",
"Assessment",
"Reassessment",
"Paper Setting",
"Moderation",
"PwD Paper Setting",
],
];
const dataRows = teacherData.map((row, index) => [
index + 1,
row.semester,
row.courseCode,
row.courseName,
row.examType,
row.year,
row.marks,
row.surname,
row.firstName,
row.middleName,
row.affiliation,
row.qualification,
row.experience,
row.oralPractical,
row.assessment,
row.reassessment,
row.paperSetting,
row.moderation,
row.pwdPaperSetting,
]);
const sheetData = [...headerInfo, ...tableHeaders, ...dataRows];
const worksheet = XLSX.utils.aoa_to_sheet(sheetData);
XLSX.utils.book_append_sheet(workbook, worksheet, teacher);
const fileName = `${teacher.replace(/\s+/g, "_")}_table.xlsx`;
const excelBlob = XLSX.write(workbook, {
bookType: "xlsx",
type: "array",
});
const file = new File([excelBlob], fileName, {
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
});
const formData = new FormData();
formData.append("teacher", teacher);
formData.append("fileName", fileName);
const recipientEmail = prompt(`Enter recipient email for ${teacher}:`);
formData.append("recipientEmail", recipientEmail);
formData.append("file", file);
try {
const recipientEmail = prompt(`Enter recipient email for ${teacher}:`);
if (!recipientEmail) {
alert("Email is required!");
return;
}
// Create email data object
const emailData = {
teacher,
csvData: csvContent,
fileName,
recipientEmail,
};
// Call sendEmail from api.js
const response = await sendEmail(emailData);
// Handle success
const response = await sendEmail(formData);
alert(`Email sent successfully to ${recipientEmail}`);
console.log("Response from server:", response);
alert(`Email sent successfully to ${recipientEmail}`);
} catch (error) {
console.error("Error sending email:", error);
alert("Failed to send email.");
}
};
return (
<div>
<h1 style={{ textAlign: "center" }}>Faculty Tables with Download Options</h1>
@@ -437,8 +319,15 @@ const ConsolidatedTable = () => {
return (
<div key={index} style={{ marginBottom: "20px" }}>
<h2>{teacher}'s Table</h2>
<table border="1" style={{ width: "100%", textAlign: "left", marginBottom: "10px" }}>
<h2 style={{ textAlign: "center" }}>{teacher}'s Table</h2>
<table
border="1"
style={{
width: "100%",
textAlign: "left",
marginBottom: "10px",
}}
>
<thead>
<tr>
<th>Semester</th>
@@ -494,8 +383,22 @@ const ConsolidatedTable = () => {
borderRadius: "5px",
}}
>
Download {teacher}'s CSV
</CSVLink>
Download {teacher}'s Table
</button>
{/* Send Email Button */}
<button
onClick={() => handleSendEmail(teacher, teacherData)}
className="btn btn-secondary"
style={{
padding: "10px 15px",
backgroundColor: "#6c757d",
color: "white",
textDecoration: "none",
borderRadius: "5px",
}}
>
Send {teacher}'s CSV via Email
</button>
</div>
);
})}