Prompt Detail:
To parse table data from a form to another EJS view and export it to an Excel sheet in an Express app, you can follow the steps below:
- In your app.js file, install the necessary modules:
express
,body-parser
,ejs
,exceljs
, andfs
by running the following command:
cssnpm install express body-parser ejs exceljs fs --save
- Create an Express application and set up the middleware to parse the request body:
phpconst express = require('express');
const bodyParser = require('body-parser');
const app = express();
// Set up middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
- Create the EJS views for the form and the table:
php// form.ejs
<form action="/main" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<label for="age">Age:</label>
<input type="number" id="age" name="age">
<button type="submit">Submit</button>
</form>
// main.ejs
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<% for(let i=0; i<data.length; i++) { %>
<tr>
<td><%= data[i].name %></td>
<td><%= data[i].age %></td>
</tr>
<% } %>
</tbody>
</table>
- Handle the form submission in your app.js file and render the main.ejs view with the table data:
javascript// Handle form submission
app.post('/main', (req, res) => {
const name = req.body.name;
const age = req.body.age;
// Render main.ejs with table data
res.render('main', { data: [{ name, age }] });
});
- Export the table data to an Excel sheet using the
exceljs
module:
javascript// Export table data to Excel sheet
app.get('/export', (req, res) => {
const workbook = new ExcelJS.Workbook();
const worksheet = workbook.addWorksheet('Data');
worksheet.columns = [
{ header: 'Name', key: 'name', width: 30 },
{ header: 'Age', key: 'age', width: 10 },
];
const data = [
{ name: 'John Doe', age: 25 },
{ name: 'Jane Smith', age: 30 },
{ name: 'Bob Johnson', age: 40 },
];
worksheet.addRows(data);
workbook.xlsx.writeFile('data.xlsx')
.then(() => {
console.log('File saved!');
res.send('File saved!');
})
.catch((err) => {
console.log(err);
res.send('Error!');
});
});
This code will create an Excel workbook with a worksheet named "Data" and add the table data to it. Then it will save the workbook to a file named "data.xlsx" and send a response to the client indicating whether the operation was successful or not. Note that you may need to modify this code to suit your specific needs.