mongo_to_execl.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. # 导入必要的库
  2. from pymongo import MongoClient
  3. import pandas as pd
  4. def export_to_excel(db_name, collection_name, fields, output_file):
  5. """
  6. 从MongoDB导出特定字段到Excel文件。
  7. 参数:
  8. - db_name: 数据库名称
  9. - collection_name: 集合名称
  10. - fields: 要导出的字段列表(例如 ['name', 'age'])
  11. - output_file: 输出的Excel文件名
  12. """
  13. # 连接到MongoDB
  14. client = MongoClient('mongodb://192.168.3.149:27180/')
  15. db = client[db_name]
  16. collection = db[collection_name]
  17. # 构建查询和投影
  18. projection = {field: 1 for field in fields}
  19. # 查询数据
  20. data = collection.find({"flag":3},projection)
  21. # 将数据转换为DataFrame
  22. df = pd.DataFrame(list(data))
  23. # 导出到Excel文件
  24. df.to_excel(output_file, index=False)
  25. if __name__ == "__main__":
  26. # 连接到 MongoDB
  27. db_name = 'data_quality' # 替换为你的数据库名称
  28. # collection_name = 'standard_sample_data_all' # 替换为你的集合名称
  29. collection_name = 'bidding_20241128_ai' # 替换为你的集合名称
  30. # 定义参数
  31. fields = ['_id', 'site','toptype','subtype','area','city','buyer','projectname','projectcode','budget','s_winner','bidamount','multipackage','href','jyhref'] # 替换为你需要导出的字段
  32. output_file = 'output.xlsx'
  33. # 调用函数导出数据
  34. export_to_excel(db_name, collection_name, fields, output_file)
  35. print(f"数据已成功导出到 {output_file}")