You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

HTML/Javascript自动加载同目录CSV及适配列数技术问询

Solution for Auto-Loading CSV & Dynamic Column Adaptation

Hey there! Let's fix your two key issues step by step—getting the CSV to load automatically on page start, and making the table work with any number of columns instead of being locked to 9. Here's how to revamp your code:


1. Auto-Load the Same-Directory CSV (No Manual File Selection)

The original FileReader setup is designed for users picking local files via the browser, but since you're running a Python web server, you can directly fetch the CSV file from the server (same directory as your HTML) using fetch(). This lets the page load the file automatically without any user input.

First, we'll remove the file input from your HTML since it's no longer needed. Then we'll update the JavaScript to use fetch instead of FileReader, and set up a repeating interval to refresh the data at your desired rate.


2. Adapt to Any Number of CSV Columns

Instead of hardcoding 9 <td> elements, we'll loop through each row's split values to generate table cells dynamically. We'll also ditch the fixed <col> tags that restricted you to 9 columns—now the table will expand or shrink to match whatever column count your CSV uses.


Updated Full Code

Monitoring.htm

<!DOCTYPE html>
<html>
<head>
    <title>Daily Monitoring</title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css">
    <meta charset="UTF-8">
</head>
<body>
    <h3>Live CSV Monitoring</h3>
    <div id="data"></div>
    <script src="FileReader.js"></script>
</body>
</html>

FileReader.js

// Define your CSV filename here (must be in the same directory as HTML)
const CSV_FILENAME = "your-file.csv";
// Refresh interval in milliseconds (5000 = 5 seconds)
const REFRESH_INTERVAL = 5000;

function loadAndRenderCSV() {
    fetch(CSV_FILENAME)
        .then(response => {
            if (!response.ok) {
                throw new Error("Could not load CSV file");
            }
            return response.text();
        })
        .then(csvText => {
            // Split CSV into rows and filter out empty lines
            const rows = csvText.split("\n").filter(row => row.trim() !== "");
            if (rows.length === 0) {
                document.getElementById("data").innerHTML = "<p>No data found in CSV</p>";
                return;
            }

            // Build the table dynamically
            let html = '<table border="1">';
            
            // Loop through each row to create table rows
            rows.forEach((rowData) => {
                const columns = rowData.split(",");
                html += "<tr>";
                
                // Loop through each column value to create table cells
                columns.forEach(colValue => {
                    // Trim whitespace for cleaner display
                    html += `<td>${colValue.trim()}</td>`;
                });
                
                html += "</tr>";
            });
            
            html += "</table>";
            document.getElementById("data").innerHTML = html;
            document.getElementById("data").style.color = "blue";
        })
        .catch(error => {
            document.getElementById("data").innerHTML = `<p>Error loading CSV: ${error.message}</p>`;
            console.error(error);
        });
}

// Load CSV immediately when the page loads
loadAndRenderCSV();
// Set up automatic refresh
setInterval(loadAndRenderCSV, REFRESH_INTERVAL);

Key Notes to Make This Work:

  • Replace your-file.csv in FileReader.js with your actual CSV filename (ensure it's in the same folder as Monitoring.htm).
  • Start your Python web server in the project folder with this command:
    python -m http.server 8000
    
  • Expose the server with ngrok using:
    ngrok http 8000
    
  • Your CSV should have consistent column counts across rows (the table will look cleaner this way—you can add extra validation if needed for messy CSVs).
  • Adjust REFRESH_INTERVAL to change how often the page refreshes the data (5000ms = 5 seconds, tweak as needed).

内容的提问来源于stack exchange,提问作者DarkOrion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:08:44