mongo_to_execl.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # 导入必要的库
  2. from pymongo import MongoClient
  3. import pandas as pd
  4. import pytz # 用于处理时区
  5. def export_to_excel(db_name, collection_name, fields, output_file):
  6. """
  7. 从MongoDB导出特定字段到Excel文件。
  8. 参数:
  9. - db_name: 数据库名称
  10. - collection_name: 集合名称
  11. - fields: 要导出的字段列表(例如 ['name', 'age'])
  12. - output_file: 输出的Excel文件名
  13. """
  14. # 连接到MongoDB
  15. client = MongoClient('mongodb://172.20.45.129:27002/')
  16. # client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True) # 清洗库
  17. db = client[db_name]
  18. collection = db[collection_name]
  19. # 构建查询和投影
  20. projection = {field: 1 for field in fields}
  21. # 查询数据
  22. data = collection.find({"mark_1": 1},projection).sort("_id", -1)
  23. # 将数据转换为DataFrame
  24. df = pd.DataFrame(list(data))
  25. # 转换时间戳字段
  26. time_fields = ['bidopentime', 'bidendtime']
  27. for field in time_fields:
  28. if field in df.columns:
  29. # 1. 转换为 datetime 对象(秒级时间戳)
  30. df[field] = pd.to_datetime(df[field], unit='s', errors='coerce')
  31. # 2. 转换为北京时间(UTC+8)
  32. beijing_tz = pytz.timezone('Asia/Shanghai')
  33. df[field] = df[field].dt.tz_localize('UTC').dt.tz_convert(beijing_tz)
  34. # 3. 去掉时区信息,保留纯时间(否则Excel可能显示异常)
  35. df[field] = df[field].dt.tz_localize(None)
  36. # 导出到Excel文件
  37. df.to_excel(output_file, index=False)
  38. if __name__ == "__main__":
  39. # 连接到 MongoDB
  40. db_name = 'wjh' # 替换为你的数据库名称
  41. # db_name = 'jyqyfw' # 替换为你的数据库名称
  42. # collection_name = 'standard_sample_data_all_ai' # 替换为你的集合名称
  43. collection_name = 'unicom_1_2' # 替换为你的集合名称
  44. # 定义参数
  45. fields = ['_id','site','toptype','subtype','area','city','buyer','projectname','projectcode','budget','s_winner','bidamount','bidopentime','bidendtime','label','href','jybxhref','spidercode'] # 替换为你需要导出的字段
  46. # fields = ['_id','id','site','href','jybxhref','spidercode','projectinfo'] # 替换为你需要导出的字段
  47. output_file = 'output.xlsx'
  48. # 调用函数导出数据
  49. export_to_excel(db_name, collection_name, fields, output_file)
  50. print(f"数据已成功导出到 {output_file}")