csv_export.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import csv
  2. import pandas as pd
  3. from sqlalchemy import create_engine
  4. from database import conn_string
  5. def convert_data(element):
  6. txt = str(element)
  7. txt = txt.replace("None", "")
  8. txt = txt.replace("False", "0").replace("True", "1")
  9. txt = txt.replace("\t", "").replace("\r", "").replace("\n", "")
  10. txt = txt.replace("\x81", "").replace("\x90", "")
  11. txt = "" if txt in ["nan", "NaT"] else txt
  12. return txt
  13. def table_to_csv(table_name: str, csv_file: str, dsn: str):
  14. try:
  15. conn = create_engine(dsn).connect().execution_options(stream_results=True)
  16. df = pd.read_sql(f"SELECT * FROM {table_name}", conn, chunksize=1000)
  17. except Exception as e:
  18. print(e.args[1])
  19. with open(csv_file, "w", encoding="latin-1", errors="replace", newline="") as fwh:
  20. print("Kopiervorgang wird gestartet...")
  21. i = 0
  22. for chunk in df:
  23. chunk.to_csv(fwh, ";", index=False, decimal=",", quoting=csv.QUOTE_NONNUMERIC)
  24. i += chunk.shape[0]
  25. if chunk.shape[0] == 1000:
  26. print(f"1000 Zeilen zum SQL Server gesendet. Insgesamt gesendet: {i}")
  27. print("")
  28. print(f"{i} Zeilen kopiert.")
  29. if __name__ == "__main__":
  30. dsn = {
  31. "user": "sa",
  32. "password": "Mffu3011#",
  33. "server": "localhost\\GLOBALCUBE",
  34. "database": "OPTIMA",
  35. "driver": "mssql",
  36. "schema": "import",
  37. }
  38. conn_str = conn_string(dsn)
  39. table_to_csv("load.Aftersales_Rechnungen_ben_AW_final", "Aftersales_Rechnungen_ben_AW_final.csv", conn_str)
  40. # print(timeit.timeit(s))