<div class="container">
<h1>Export Array to CSV</h1>
<p class="subtitle">Convert JavaScript objects to CSV format and download</p>
<div class="data-preview">
<h3>Sample Data</h3>
<table id="dataTable">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
</table>
</div>
<button class="btn-export" onclick="exportToCSV()">
<svg class="icon" fill="currentColor" viewBox="0 0 20 20">
<path d="M13 8V2H7v6H2l8 8 8-8h-5zM0 18h20v2H0v-2z"/>
</svg>
Export to CSV
</button>
<div class="success-message" id="successMessage">
✓ CSV file downloaded successfully!
</div>
</div>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background: linear-gradient(135deg, #E30B5C 0%, #8B0A3D 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
padding: 40px;
max-width: 800px;
width: 100%;
}
h1 {
font-size: 28px;
color: #1a1a1a;
margin-bottom: 10px;
}
.subtitle {
color: #666;
margin-bottom: 30px;
font-size: 14px;
}
.data-preview {
background: #f8f9fa;
border-radius: 8px;
padding: 20px;
margin-bottom: 30px;
max-height: 300px;
overflow-y: auto;
}
.data-preview h3 {
font-size: 14px;
color: #666;
margin-bottom: 15px;
text-transform: uppercase;
letter-spacing: 0.5px;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
th, td {
text-align: left;
padding: 12px;
border-bottom: 1px solid #e0e0e0;
}
th {
background: #fff;
color: #E30B5C;
font-weight: 600;
position: sticky;
top: 0;
}
td {
color: #333;
}
.btn-export {
background: linear-gradient(135deg, #E30B5C 0%, #8B0A3D 100%);
color: white;
border: none;
padding: 14px 32px;
font-size: 16px;
font-weight: 500;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(227, 11, 92, 0.3);
display: flex;
align-items: center;
gap: 10px;
margin: 0 auto;
}
.btn-export:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(227, 11, 92, 0.4);
}
.btn-export:active {
transform: translateY(0);
}
.icon {
width: 20px;
height: 20px;
}
.success-message {
background: #d4edda;
color: #155724;
padding: 12px 20px;
border-radius: 8px;
margin-top: 20px;
display: none;
text-align: center;
font-size: 14px;
}
.success-message.show {
display: block;
animation: slideIn 0.3s ease;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateY(-10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
// Sample data - array of objects
const data = [
{ id: 1, name: 'John Doe', email: 'john@example.com', department: 'Engineering', salary: 85000 },
{ id: 2, name: 'Jane Smith', email: 'jane@example.com', department: 'Marketing', salary: 72000 },
{ id: 3, name: 'Bob Johnson', email: 'bob@example.com', department: 'Sales', salary: 68000 },
{ id: 4, name: 'Alice Williams', email: 'alice@example.com', department: 'HR', salary: 65000 },
{ id: 5, name: 'Charlie Brown', email: 'charlie@example.com', department: 'Engineering', salary: 92000 }
];
// Function to convert array of objects to CSV
function arrayToCSV(arr) {
if (!arr || arr.length === 0) return '';
// Get headers from the first object
const headers = Object.keys(arr[0]);
// Create CSV rows
const csvRows = [];
// Add header row
csvRows.push(headers.join(','));
// Add data rows
for (const row of arr) {
const values = headers.map(header => {
const val = row[header];
// Handle values that contain commas or quotes
return `"${String(val).replace(/"/g, '""')}"`;
});
csvRows.push(values.join(','));
}
return csvRows.join('\n');
}
// Function to download CSV file
function downloadCSV(csv, filename = 'export.csv') {
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
if (link.download !== undefined) {
const url = URL.createObjectURL(blob);
link.setAttribute('href', url);
link.setAttribute('download', filename);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
// Main export function
function exportToCSV() {
const csv = arrayToCSV(data);
const timestamp = new Date().toISOString().slice(0, 10);
downloadCSV(csv, `data_export_${timestamp}.csv`);
// Show success message
const msg = document.getElementById('successMessage');
msg.classList.add('show');
setTimeout(() => {
msg.classList.remove('show');
}, 3000);
}
// Populate table with sample data
function populateTable() {
const tbody = document.getElementById('tableBody');
data.forEach(row => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${row.id}</td>
<td>${row.name}</td>
<td>${row.email}</td>
<td>${row.department}</td>
<td>$${row.salary.toLocaleString()}</td>
`;
tbody.appendChild(tr);
});
}
// Initialize
populateTable();
No comments yet. Be the first!