How to display text file data in html table?

by cortez.connelly , in category: HTML & CSS , 9 months ago

How to display text file data in html table?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by darrion.kuhn , 5 months ago

@cortez.connelly 

To display text file data in an HTML table, you can use JavaScript to read the text file and then parse the data into rows and columns of a table. Here's an example code snippet that shows how to do this:

  1. First, create an HTML file with a table element where you want to display the data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text File Data Table</title>
</head>
<body>
<table id="data-table">
</table>
<script src="script.js"></script>
</body>
</html>


  1. Next, create a JavaScript file (script.js) to read the text file and populate the table with the data:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const table = document.getElementById('data-table');

fetch('data.txt')
  .then(response => response.text())
  .then(data => {
    const rows = data.split('
');

    rows.forEach(row => {
      const cells = row.split(',');
      const tr = document.createElement('tr');
      
      cells.forEach(cellData => {
        const td = document.createElement('td');
        td.textContent = cellData.trim();
        tr.appendChild(td);
      });
      
      table.appendChild(tr);
    });
  })
  .catch(error => console.error('Error:', error));


  1. Create a text file (data.txt) with your data in a comma-separated format:
1
2
3
4
Name, Age, City
John Doe, 30, New York
Jane Smith, 25, Los Angeles
Alice Johnson, 35, Chicago


  1. Place the script.js file and data.txt file in the same directory as the HTML file.


When you open the HTML file in a browser, it will display the data from the text file in a table format on the page. Each line in the text file will be a row in the table, with columns separated by commas.