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

如何将超2000条记录的CSV转换为带折叠/展开功能的HTML?

Convert Large CSV to HTML with Collapsible Sections

Absolutely! Converting your 2000+ record CSV to HTML with collapsible groups (like by ServerName) is totally doable, and Python is a great tool for this job—it’s efficient with large datasets and makes generating dynamic HTML straightforward.

Here’s a step-by-step solution that groups your data by ServerName (you can adjust this to group by other columns like Environment or Team if needed) and creates an HTML file with collapsible sections using native HTML5 <details> and <summary> tags (no external JavaScript required):

Step 1: Python Script to Generate Collapsible HTML

Save this as csv_to_collapsible_html.py:

import csv
from itertools import groupby
from operator import itemgetter

def csv_to_collapsible_html(input_csv, output_html):
    # Read CSV data
    with open(input_csv, 'r', newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        rows = list(reader)
        if not rows:
            print("No data found in CSV.")
            return
    
    # Sort rows by ServerName (required for groupby to work correctly)
    sorted_rows = sorted(rows, key=itemgetter('ServerName'))
    
    # Start building HTML content
    html_content = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Collapsible Server Permissions</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 20px; }
            table { border-collapse: collapse; width: 100%; margin-top: 10px; }
            th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
            th { background-color: #f2f2f2; }
            details { margin-bottom: 10px; border: 1px solid #eee; border-radius: 4px; padding: 10px; }
            summary { font-weight: bold; cursor: pointer; padding: 5px; }
            summary:hover { background-color: #f5f5f5; }
            .record-count { color: #666; font-weight: normal; margin-left: 10px; }
        </style>
    </head>
    <body>
        <h1>Server Permissions Overview</h1>
    """
    
    # Group rows by ServerName and add collapsible sections to HTML
    for server_name, group in groupby(sorted_rows, key=itemgetter('ServerName')):
        group_rows = list(group)
        record_count = len(group_rows)
        
        # Add collapsible section for the server
        html_content += f"""
        <details>
            <summary>{server_name} <span class="record-count">({record_count} records)</span></summary>
            <table>
                <thead>
                    <tr>
        """
        # Add table headers
        for header in reader.fieldnames:
            html_content += f"<th>{header}</th>"
        html_content += """
                    </tr>
                </thead>
                <tbody>
        """
        # Add table rows for the group
        for row in group_rows:
            html_content += "<tr>"
            for header in reader.fieldnames:
                html_content += f"<td>{row[header]}</td>"
            html_content += "</tr>"
        
        html_content += """
                </tbody>
            </table>
        </details>
        """
    
    # Close HTML tags
    html_content += """
    </body>
    </html>
    """
    
    # Write to output file
    with open(output_html, 'w', encoding='utf-8') as f:
        f.write(html_content)
    
    print(f"Successfully generated {output_html} with {len(rows)} records grouped by ServerName.")

# Run the function (update input and output paths as needed)
if __name__ == "__main__":
    input_csv_path = "your_input.csv"  # Replace with your CSV file path
    output_html_path = "collapsible_permissions.html"  # Output HTML file path
    csv_to_collapsible_html(input_csv_path, output_html_path)

Step 2: How to Use the Script

  1. Replace your_input.csv with the path to your actual CSV file.
  2. Run the script using Python:
    python csv_to_collapsible_html.py
    
  3. Open the generated collapsible_permissions.html file in any modern browser—you’ll see each server as a collapsible section, showing/hiding its records when clicked.

Customization Tips

  • Change Grouping Column: To group by Environment instead of ServerName, replace all instances of itemgetter('ServerName') with itemgetter('Environment').
  • Adjust Styling: Modify the CSS in the <style> section to match your preferred colors, fonts, or spacing.
  • Add Nested Collapsibles: If you want multi-level grouping (e.g., first by Environment, then by ServerName), nest the groupby calls—just sort by the parent column first, then the child column.

This approach handles 2000+ records easily, and the native HTML5 collapsible elements work smoothly in all modern browsers without extra dependencies.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:22:47