吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1737|回复: 6
收起左侧

[其他原创] 分享一个用AI写的纯html实现的json数据转csv文件实现

[复制链接]
wxk0248 发表于 2025-5-1 11:28
最近碰到一个场景,想要把json对象数组转成为excel表格的形式展现,便于复制整列数据、整行数据。
期望可以脱机使用,不要很笨重,最好不依赖网络。输出文件上,由于excel文件本身比较笨重,考虑可以使用csv文件替代,csv文件同样可以使用excel打开。
以上功能原生html应该就可以实现,所以使用deepseek尝试了一下,达到了预期效果,源码如下:

[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON转CSV转换器</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        textarea {
            width: 100%;
            height: 200px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            resize: vertical;
        }
        button {
            padding: 10px 15px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #45a049;
        }
        #result {
            margin-top: 20px;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-height: 100px;
            white-space: pre-wrap;
            background-color: #f9f9f9;
        }
        .error {
            color: red;
            margin-top: 10px;
        }
        .button-group {
            display: flex;
            gap: 10px;
        }
        #downloadBtn {
            background-color: #2196F3;
        }
        #downloadBtn:hover {
            background-color: #0b7dda;
        }
    </style>
</head>
<body>
    <h1>JSON数组转换为CSV</h1>
    <div class="container">
        <label for="jsonInput">请输入JSON数组:</label>
        <textarea id="jsonInput" placeholder='例如:[{"name":"张三","age":25,"city":"北京"},{"name":"李四","age":30,"city":"上海"}]'>[{"name":"张三","age":25,"city":"北京"},{"name":"李四","age":30,"city":"上海"}]</textarea>
        <div class="button-group">
            <button id="convertBtn">转换为CSV</button>
            <button id="downloadBtn" disabled>下载CSV文件</button>
        </div>
        <div id="error" class="error"></div>
        <label for="result">CSV结果:</label>
        <div id="result"></div>
    </div>

    <script>
        let currentCsv = ''; // 存储当前转换的CSV内容
        
        document.getElementById('convertBtn').addEventListener('click', function() {
            const jsonInput = document.getElementById('jsonInput').value.trim();
            const resultDiv = document.getElementById('result');
            const errorDiv = document.getElementById('error');
            const downloadBtn = document.getElementById('downloadBtn');
            
            // 清空之前的错误和结果
            errorDiv.textContent = '';
            resultDiv.textContent = '';
            downloadBtn.disabled = true;
            
            if (!jsonInput) {
                errorDiv.textContent = '请输入JSON内容';
                return;
            }
            
            try {
                // 解析JSON输入
                const jsonArray = JSON.parse(jsonInput);
                
                if (!Array.isArray(jsonArray)) {
                    errorDiv.textContent = '输入的不是JSON数组';
                    return;
                }
                
                if (jsonArray.length === 0) {
                    errorDiv.textContent = 'JSON数组为空';
                    return;
                }
                
                // 转换为CSV
                currentCsv = convertJsonToCsv(jsonArray);
                
                // 显示结果
                resultDiv.textContent = currentCsv;
                
                // 启用下载按钮
                downloadBtn.disabled = false;
            } catch (e) {
                errorDiv.textContent = 'JSON解析错误: ' + e.message;
            }
        });
        
        // 下载按钮点击事件
        document.getElementById('downloadBtn').addEventListener('click', function() {
            if (!currentCsv) {
                document.getElementById('error').textContent = '没有可下载的CSV内容';
                return;
            }
            
            // 添加UTF-8 BOM头,解决Excel中文乱码问题
            const bom = '\uFEFF';
            const csvWithBom = bom + currentCsv;
            
            // 创建一个Blob对象,指定编码为UTF-8
            const blob = new Blob([csvWithBom], { type: 'text/csv;charset=utf-8;' });
            
            // 创建一个下载链接
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            // 设置下载属性
            link.setAttribute('href', url);
            link.setAttribute('download', 'data.csv');
            link.style.visibility = 'hidden';
            
            // 添加到DOM并触发点击
            document.body.appendChild(link);
            link.click();
            
            // 清理
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
        });
        
        /**
         * 将JSON数组转换为CSV字符串
         * [url=home.php?mod=space&uid=952169]@Param[/url] {Array} jsonArray - JSON对象数组
         * @returns {string} CSV格式的字符串
         */
        function convertJsonToCsv(jsonArray) {
            // 收集所有可能的列标题
            const headers = new Set();
            jsonArray.forEach(item => {
                Object.keys(item).forEach(key => {
                    headers.add(key);
                });
            });
            
            // 将Set转换为数组
            const headerArray = Array.from(headers);
            
            // 构建CSV内容
            let csv = '';
            
            // 添加标题行
            csv += headerArray.join(',') + '\n';
            
            // 添加数据行
            jsonArray.forEach(item => {
                const row = headerArray.map(header => {
                    // 处理值中的逗号和换行符
                    let value = item[header] !== undefined ? item[header] : '';
                    if (typeof value === 'string') {
                        // 如果值包含逗号、换行符或双引号,需要用双引号包裹
                        if (value.includes(',') || value.includes('\n') || value.includes('"')) {
                            // 转义双引号
                            value = value.replace(/"/g, '""');
                            value = `"${value}"`;
                        }
                    }
                    return value;
                });
                csv += row.join(',') + '\n';
            });
            
            return csv;
        }
    </script>
</body>
</html>


20250501.png

免费评分

参与人数 1吾爱币 +3 热心值 +1 收起 理由
苏紫方璇 + 3 + 1 欢迎分析讨论交流,吾爱破解论坛有你更精彩!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

sunflash 发表于 2025-5-1 20:20
厉害厉害,感觉很有用。感谢分享,共同进步
52PJ070 发表于 2025-5-2 22:18
jxc1690 发表于 2025-5-5 22:11
 楼主| wxk0248 发表于 2025-5-5 23:10
jxc1690 发表于 2025-5-5 22:11
这不是js写的么 我还以为html可以写逻辑了

啊,我本意的表达是使用一个html文件实现,html语言是声明式的,本身肯定写不了逻辑的啊
yxf515321 发表于 2025-5-6 09:47
json的嵌套好复杂,对于大型的那种好用吗
 楼主| wxk0248 发表于 2025-5-6 11:05
yxf515321 发表于 2025-5-6 09:47
json的嵌套好复杂,对于大型的那种好用吗

只支持简单json对象数组,对象属性值只能是简单类型。如果对象套对象,那就是多维表格了,肯定不支持的,那个实现会巨复杂
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2026-3-26 02:51

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表