mongo_to_execl.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. # client = MongoClient('mongodb://127.0.0.1:27087/', unicode_decode_error_handler="ignore",directConnection=True) # 清洗库
  18. db = client[db_name]
  19. collection = db[collection_name]
  20. # 构建查询和投影
  21. projection = {field: 1 for field in fields}
  22. # 查询数据
  23. data = collection.find({"tag": 11},projection).sort("_id", 1)
  24. # 将数据转换为DataFrame
  25. df = pd.DataFrame(list(data))
  26. # # 转换时间戳字段
  27. # time_fields = ['bidopentime', 'bidendtime']
  28. # for field in time_fields:
  29. # if field in df.columns:
  30. # # 1. 转换为 datetime 对象(秒级时间戳)
  31. # df[field] = pd.to_datetime(df[field], unit='s', errors='coerce')
  32. # # 2. 转换为北京时间(UTC+8)
  33. # beijing_tz = pytz.timezone('Asia/Shanghai')
  34. # df[field] = df[field].dt.tz_localize('UTC').dt.tz_convert(beijing_tz)
  35. # # 3. 去掉时区信息,保留纯时间(否则Excel可能显示异常)
  36. # df[field] = df[field].dt.tz_localize(None)
  37. # 导出到Excel文件
  38. df.to_excel(output_file, index=False)
  39. if __name__ == "__main__":
  40. # 连接到 MongoDB
  41. db_name = 'jyqyfw' # 替换为你的数据库名称
  42. # db_name = 'jyqyfw' # 替换为你的数据库名称
  43. # collection_name = 'standard_sample_data_all_ai' # 替换为你的集合名称
  44. # collection_name = 'xzh_20250714' # 替换为你的集合名称
  45. collection_name = 'xzh_20250714_1' # 替换为你的集合名称
  46. # 定义参数
  47. # fields = ['_id','id','site','toptype','subtype','area','city','buyer','projectname','projectcode','budget','s_winner','bidamount','label','href','jybxhref','package'] # 替换为你需要导出的字段
  48. # fields = ['id','site','toptype','subtype','area','city','buyer','projectname','projectcode','budget','s_winner','bidamount','label','href','jybxhref'] # 替换为你需要导出的字段
  49. fields = ['id','title','projectname','href','projectcode','subtype','s_winner','bidamount','buyer'] # 替换为你需要导出的字段
  50. output_file = 'output.xlsx'
  51. # 调用函数导出数据
  52. export_to_excel(db_name, collection_name, fields, output_file)
  53. print(f"数据已成功导出到 {output_file}")