You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.9 KiB
86 lines
2.9 KiB
import os
|
|
import openpyxl
|
|
|
|
# 文件路径
|
|
output_file = r'D:\计量经济学\计量实验资料及作业要求\计量实验资料及作业要求\UGC回归数据.xlsx'
|
|
|
|
print("========================================")
|
|
print(" 创建Excel文件并填充数据")
|
|
print("========================================")
|
|
print(f"输出文件: {output_file}")
|
|
print()
|
|
|
|
# 检查输出目录是否存在
|
|
output_dir = os.path.dirname(output_file)
|
|
print(f"输出目录: {output_dir}")
|
|
print(f"目录存在: {os.path.exists(output_dir)}")
|
|
|
|
if not os.path.exists(output_dir):
|
|
print("正在创建输出目录...")
|
|
try:
|
|
os.makedirs(output_dir)
|
|
print("目录创建成功")
|
|
except Exception as e:
|
|
print(f"创建目录失败: {e}")
|
|
exit(1)
|
|
|
|
# 创建Excel文件
|
|
try:
|
|
print("\n创建Excel文件...")
|
|
wb = openpyxl.Workbook()
|
|
ws = wb.active
|
|
|
|
# 写入表头
|
|
headers = ['Y', 'X1', 'X2', 'X3', 'X4', 'X5', 'X6']
|
|
for i, header in enumerate(headers, 1):
|
|
ws.cell(row=1, column=i, value=header)
|
|
|
|
# 写入示例数据(前10行)
|
|
print("填充示例数据...")
|
|
for i in range(1, 11):
|
|
ws.cell(row=i+1, column=1, value=i * 0.5) # Y: UGC有用性
|
|
ws.cell(row=i+1, column=2, value=i * 2) # X1: 评论数量
|
|
ws.cell(row=i+1, column=3, value=i * 10) # X2: 评论长度
|
|
ws.cell(row=i+1, column=4, value=i * 2) # X3: 评论复杂度
|
|
ws.cell(row=i+1, column=5, value=5.0) # X4: 评论可读性
|
|
ws.cell(row=i+1, column=6, value=(i % 3) - 1) # X5: 内容情感性
|
|
ws.cell(row=i+1, column=7, value=i * 0.3) # X6: 信息丰富度
|
|
|
|
# 保存文件
|
|
print("保存文件...")
|
|
wb.save(output_file)
|
|
|
|
print(f"文件已成功创建: {output_file}")
|
|
print(f"文件大小: {os.path.getsize(output_file) / 1024:.2f} KB")
|
|
|
|
# 验证文件
|
|
print("\n验证文件...")
|
|
if os.path.exists(output_file):
|
|
print("文件创建成功!")
|
|
# 重新打开文件读取内容
|
|
wb_check = openpyxl.load_workbook(output_file)
|
|
ws_check = wb_check.active
|
|
print(f"工作表名称: {ws_check.title}")
|
|
print(f"行数: {ws_check.max_row}")
|
|
print(f"列数: {ws_check.max_column}")
|
|
|
|
# 显示前5行
|
|
print("\n前5行数据:")
|
|
for row in range(1, min(6, ws_check.max_row + 1)):
|
|
row_data = []
|
|
for col in range(1, ws_check.max_column + 1):
|
|
value = ws_check.cell(row=row, column=col).value
|
|
row_data.append(value)
|
|
print(f"行 {row}: {row_data}")
|
|
else:
|
|
print("文件创建失败!")
|
|
|
|
print()
|
|
print("========================================")
|
|
print(" 任务完成")
|
|
print("========================================")
|
|
|
|
except Exception as e:
|
|
print(f"处理文件时出错: {str(e)}")
|
|
import traceback
|
|
traceback.print_exc()
|
|
|