使用Python将MySql中的数据导入到Ms.Excel ListObject中

问题描述 投票:0回答:1

我正在尝试自动化一个过程,我们需要将数据从 MySQL 数据库导入到

ListObject
(Ms.Excel 表)。

环境: 2021年Office专业女士 Windows 10 专业版 Python 3.12.1

代码如下:

import mysql.connector
import pandas as pd
from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from datetime import datetime
import mysql.connector
import xlwings as xw

today = datetime.now()
test_file_path = rf"E:\ReconTest\Reconcilation Reports\QF\2025\Jan\QF - January Internal Reconciliation Summary.xlsx"

QUERY = f"""
        SELECT *
        FROM dailyfiledto
        WHERE Cust = 'QF' AND fdate = '{today.strftime('%Y-%m-%d')}'
      """

def mysql_to_excel_listobject(query,
                              excel_file, sheet_name, listobject_name,
                              start_row, start_col):
  """
  Fetches data from MySQL, loads it into a Pandas DataFrame,
  and writes it to a specified Excel ListObject.

  Args:
    query: SQL query to execute.
    excel_file: Path to the Excel file.
    sheet_name: Name of the sheet containing the ListObject.
    listobject_name: Name of the ListObject.
    start_row: Starting row index for data insertion (1-indexed).
    start_col: Starting column index for data insertion (1-indexed).
  """

  try:
    # Connect to MySQL database
    conn = mysql.connector.connect(
        host="localhost",
        user="root",
        password="",
        database="azm"
    )
    cursor = conn.cursor()

    # Execute the SQL query
    cursor.execute(query)


    # Fetch all rows from the result
    data = cursor.fetchall()
    # print(str(len(data)))

    # Create a Pandas DataFrame from the fetched data
    df = pd.DataFrame(data)


    # Open the Excel workbook
    wb = xw.Book(excel_file)
    sheet = wb.sheets[sheet_name]

    # Get the ListObject by name
    listobject = sheet.range(listobject_name).listobject

    # Calculate the starting cell address for data insertion
    start_cell = xw.Range(sheet, row=start_row, column=start_col).address

    # Clear existing data within the ListObject (optional)
    listobject.data_body_range.clear_contents()

    # Write the DataFrame data to the ListObject
    df.to_excel(
        excel_file,
        sheet_name=sheet_name,
        startrow=start_row - 1,  # Adjust for 0-based indexing
        startcol=start_col - 1,  # Adjust for 0-based indexing
        index=False,
        header=False,
        engine='openpyxl'  # Use openpyxl engine for better ListObject support
    )

    # Save the changes to the Excel file
    wb.save()

  except Exception as e:
    print(f"Error: {e}")

  finally:
    # Close the database connection
    if conn:
      conn.close()


workbook = xw.Book(test_file_path)

new_sheet_name = today.strftime("%d-%b")
new_sheet = workbook.sheets[new_sheet_name]
list_object = new_sheet.tables[0]
print(list_object)
listobject_range = list_object.range

    # Write data into the list object in the new sheet
  # source_lo = workbook[new_sheet_name].tables[0]

source_lo = list_object
  # print(source_lo)
start_row = listobject_range.row + 1
  #print(start_row)
start_col = listobject_range.column
start_cell = new_sheet.range((start_row, start_col))
max_rows = listobject_range.shape[0] - 1

mysql_to_excel_listobject(QUERY,
    test_file_path, "22-Jan", source_lo,
    5, 2
)

我收到的错误是: 错误:必须是实数,而不是表格 enter image description here

使用

print()
,我确实检查了SQL查询结果的记录数是否正确,因此数据库和连接没有问题,问题是,上述错误没有指出任何特定的行或函数代码来检查任何此外,这就是我陷入困境的地方。

任何指导将不胜感激。

艾哈迈德

python excel listobject
1个回答
0
投票

提供完整的回溯很有帮助,这样可以看到行号和文本,如果没有提及,我们就知道问题发生在哪里。

问题似乎发生在这条线上

# Get the ListObject by name
    listobject = sheet.range(listobject_name).listobject

其中使用的范围是从程序主要部分获得的

listobject_name
(表),而
sheet.range()
需要一个范围。因此出现错误。

你的线路可能应该是;

listobject = sheet.range(listobject_name.range.address).table
© www.soinside.com 2019 - 2024. All rights reserved.