这是两个随机抽取上传表格中一格内容的Python程序。

 

一:使用Flask构建Web应用(推荐)

 

```python

# app.py

from flask import Flask, render_template, request, jsonify

import pandas as pd

import random

import os

 

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = 'uploads'

app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB限制

 

# 确保上传目录存在

os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)

 

@app.route('/')

def index():

    return render_template('index.html')

 

@app.route('/upload', methods=['POST'])

def upload_file():

    if 'file' not in request.files:

        return jsonify({'error': '没有文件上传'}), 400

    

    file = request.files['file']

    if file.filename == '':

        return jsonify({'error': '未选择文件'}), 400

    

    # 保存文件

    filepath = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)

    file.save(filepath)

    

    try:

        # 读取表格

        if file.filename.endswith('.csv'):

            df = pd.read_csv(filepath)

        else:

            df = pd.read_excel(filepath)

        

        # 随机抽取一格内容

        row = random.randint(0, len(df) - 1)

        col = random.randint(0, len(df.columns) - 1)

        

        result = {

            'row': row + 1, # 转为1-based索引显示

            'col': col + 1,

            'row_label': df.index[row],

            'col_label': df.columns[col],

            'value': str(df.iloc[row, col])

        }

        

        return jsonify(result)

    

    except Exception as e:

        return jsonify({'error': str(e)}), 500

    

    finally:

        # 清理临时文件

        if os.path.exists(filepath):

            os.remove(filepath)

 

if __name__ == '__main__':

    app.run(debug=True)

```

 

```html

<!-- templates/index.html -->

<!DOCTYPE html>

<html>

<head>

    <title>随机抽取表格内容</title>

    <style>

        body {

            font-family: Arial, sans-serif;

            max-width: 600px;

            margin: 50px auto;

            padding: 20px;

        }

        .upload-area {

            border: 2px dashed #ccc;

            padding: 40px;

            text-align: center;

            margin: 20px 0;

        }

        .result {

            margin-top: 20px;

            padding: 20px;

            background: #f0f0f0;

            border-radius: 5px;

            display: none;

        }

        .result.show {

            display: block;

        }

        button {

            background: #007bff;

            color: white;

            border: none;

            padding: 10px 20px;

            border-radius: 5px;

            cursor: pointer;

        }

        button:hover {

            background: #0056b3;

        }

        .error {

            color: red;

        }

        .success {

            color: green;

        }

    </style>

</head>

<body>

    <h1>📊 随机抽取表格内容</h1>

    

    <div class="upload-area">

        <h3>上传表格文件</h3>

        <p>支持 .xlsx, .xls, .csv 格式</p>

        <input type="file" id="fileInput" accept=".xlsx,.xls,.csv">

        <br><br>

        <button onclick="uploadFile()">上传并随机抽取</button>

    </div>

    

    <div id="result" class="result">

        <h3>🎯 抽取结果</h3>

        <p><strong>位置:</strong>第 <span id="rowNum"></span> 行,第 <span id="colNum"></span> 列</p>

        <p><strong>列名:</strong><span id="colLabel"></span></p>

        <p><strong>内容:</strong><span id="value" style="font-size: 24px; font-weight: bold;"></span></p>

    </div>

 

    <script>

        function uploadFile() {

            const fileInput = document.getElementById('fileInput');

            const file = fileInput.files[0];

            

            if (!file) {

                alert('请先选择文件!');

                return;

            }

            

            const formData = new FormData();

            formData.append('file', file);

            

            const resultDiv = document.getElementById('result');

            resultDiv.className = 'result';

            resultDiv.innerHTML = '<p>正在处理...</p>';

            

            fetch('/upload', {

                method: 'POST',

                body: formData

            })

            .then(response => response.json())

            .then(data => {

                if (data.error) {

                    resultDiv.className = 'result show';

                    resultDiv.innerHTML = `<p class="error">❌ 错误:${data.error}</p>`;

                    return;

                }

                

                document.getElementById('rowNum').textContent = data.row;

                document.getElementById('colNum').textContent = data.col;

                document.getElementById('colLabel').textContent = data.col_label;

                document.getElementById('value').textContent = data.value;

                resultDiv.className = 'result show';

            })

            .catch(error => {

                resultDiv.className = 'result show';

                resultDiv.innerHTML = `<p class="error">❌ 上传失败:${error.message}</p>`;

            });

        }

    </script>

</body>

</html>

```

 

二:命令行版本

 

```python

# random_pick.py

import pandas as pd

import random

import sys

 

def random_pick_from_table(filepath):

    """

    从表格文件中随机抽取一格内容

    

    Args:

        filepath: 表格文件路径 (.xlsx, .xls, .csv)

    """

    try:

        # 根据文件扩展名选择读取方式

        if filepath.endswith('.csv'):

            df = pd.read_csv(filepath)

        else:

            df = pd.read_excel(filepath)

        

        print(f"📊 表格信息:{len(df)} 行 × {len(df.columns)} 列")

        print(f"列名:{', '.join(df.columns.tolist())}\n")

        

        # 随机抽取

        row_idx = random.randint(0, len(df) - 1)

        col_idx = random.randint(0, len(df.columns) - 1)

        

        value = df.iloc[row_idx, col_idx]

        row_label = df.index[row_idx]

        col_label = df.columns[col_idx]

        

        # 显示结果

        print("🎯 随机抽取结果:")

        print(f" 位置:第 {row_idx + 1} 行,第 {col_idx + 1} 列")

        print(f" 行标签:{row_label}")

        print(f" 列名:{col_label}")

        print(f" 内容:{value}")

        

        return {

            'row': row_idx,

            'col': col_idx,

            'row_label': row_label,

            'col_label': col_label,

            'value': value

        }

        

    except FileNotFoundError:

        print(f"❌ 错误:找不到文件 '{filepath}'")

    except Exception as e:

        print(f"❌ 错误:{e}")

 

if __name__ == '__main__':

    # 使用示例

    if len(sys.argv) > 1:

        filepath = sys.argv[1]

    else:

        filepath = input("请输入表格文件路径:")

    

    random_pick_from_table(filepath)

```

 

安装依赖

 

```bash

# 安装必要的库

pip install pandas openpyxl flask

```

 

使用说明

 

Web版本:

 

1. 运行 python app.py

2. 浏览器访问 http://localhost:5000

3. 上传表格文件,点击按钮即可随机抽取

 

命令行版本:

 

```bash

python random_pick.py data.xlsx

# 或

python random_pick.py data.csv

```

 

· 支持 Excel (.xlsx, .xls) 和 CSV 文件

· 完全随机抽取任意一格内容

· 显示抽取位置(行列号)

· 显示列名和内容

· Web界面友好易用

· 自动清理临时文件

 

选择哪个版本取决于实际需求:

 

· Web版本:适合非技术用户,界面友好

· 命令行版本:适合批量处理或集成到脚本中

更多推荐