設為首頁收藏本站

艾歐踢論壇

 找回密碼
 立即註冊

QQ登錄

只需一步,快速開始

搜索
熱搜: 活動 交友 discuz
查看: 423|回復: 0
打印 上一主題 下一主題

Writing Excel Data to MySQL using Pandas

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2023-4-20 16:46:10 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
Install packages
As we are going to work with an excel using pandas and mysql database, first we need to install the required packages.
  1. pip install pandas
  2. pip install openpyxl
  3. pip install sqlalchemy
  4. pip install pymysql
複製代碼

openpyxl is required to work with .xlsx files. sqlalchemy and pymysql is required for connecting with mysql.
Be ready with a sample .xlsx file
I have created a sample employee file 'employee.xlsx' having employee's first name, last name, age and profession.
Make a connection to your mysql
You should have your MySQL database ready. create_engine() lets you create an engine instance, basically a starting point of sqlalchemy application. You have to pass here a URL string that indicates database dialect and connection parameters. Replace username, password, host, port, database with your corresponding values.
  1. from sqlalchemy import create_engineengine = create_engine("mysql+pymysql://" + "username" + ":" + "password" + "@" + "host" + ":" + "port" + "/" + "database" + "?" + "charset=utf8mb4")
複製代碼

After creating the instance, now you should establish a connection to the database using connect().
  1. conn = engine.connect()
複製代碼

Now that we have our connection established, it's time to work a little with Pandas.
Reading an excel file using Pandas
First create an excel file obj using pandas ExcelFile() and pass your filename inside.
  1. import pandas as pdexcel_file = pd.ExcelFile('employee.xlsx')
複製代碼

After creating the excel file obj, now it's time to parse the excel sheet using parse() function. Pass the sheet name that you want to process.
  1. excel_dataframe = excel_file.parse(sheet_name="employee_data")
複製代碼

And yes! The data has been copied to a dataframe.
Let's move on to the last step where we load this into our mysql table.
Load the data into mysql
To load our excel_dataframe to mysql, we use to_sql() with table name and sql connection arguments. Here I have given table name as employee_data. The parameter if_exists checks if the table already exists in the database. If yes, in this case it will append the data.
  1. excel_dataframe.to_sql("employee_data", conn, if_exists="append")
複製代碼

Don't worry if you don't have the table already. A table gets created with the name that you pass into to_sql().
Now go and query for the table results. You will see the data inserted.

method2 script
  1. import xlrd
  2. import MySQLdb

  3. # Open the workbook and define the worksheet
  4. book = xlrd.open_workbook("pytest.xls")
  5. sheet = book.sheet_by_name("source")

  6. # Establish a MySQL connection
  7. database = MySQLdb.connect (host="localhost", user = "root", passwd = "", db = "mysqlPython")

  8. # Get the cursor, which is used to traverse the database, line by line
  9. cursor = database.cursor()

  10. # Create the INSERT INTO sql query
  11. query = """INSERT INTO orders (product, customer_type, rep, date, actual, expected, open_opportunities, closed_opportunities, city, state, zip, population, region) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""

  12. # Create a For loop to iterate through each row in the XLS file, starting at row 2 to skip the headers
  13. for r in range(1, sheet.nrows):
  14.                 product               = sheet.cell(r,).value
  15.                 customer             = sheet.cell(r,1).value
  16.                 rep                     = sheet.cell(r,2).value
  17.                 date                   = sheet.cell(r,3).value
  18.                 actual                 = sheet.cell(r,4).value
  19.                 expected            = sheet.cell(r,5).value
  20.                 open                  = sheet.cell(r,6).value
  21.                 closed                = sheet.cell(r,7).value
  22.                 city                   = sheet.cell(r,8).value
  23.                 state                 = sheet.cell(r,9).value
  24.                 zip                    = sheet.cell(r,10).value
  25.                 pop                  = sheet.cell(r,11).value
  26.                 region              = sheet.cell(r,12).value

  27.                 # Assign values from each row
  28.                 values = (product, customer, rep, date, actual, expected, open, closed, city, state, zip, pop, region)

  29.                 # Execute sql Query
  30.                 cursor.execute(query, values)

  31. # Close the cursor
  32. cursor.close()

  33. # Commit the transaction
  34. database.commit()

  35. # Close the database connection
  36. database.close()

  37. # Print results
  38. print ""
  39. print "All Done! Bye, for now."
  40. print ""
  41. columns = str(sheet.ncols)
  42. rows = str(sheet.nrows)
  43. print "I just imported " %2B columns %2B " columns and " %2B rows %2B " rows to MySQL!"
複製代碼
method3

  1. import pymysql
  2. import pandas
  3. file = r'D:\Python\finreport\tablebasicinfo.xlsx'    ## 文件
  4. df = pandas.read_excel(file) ## 读文件
  5. print(df)
  6. infodata = pandas.DataFrame(df).values
  7. db = pymysql.connect(host='localhost',
  8.                      user='root',
  9.                      password='***',
  10.                      port=3307,
  11.                      database='reportdb')
  12. cursor = db.cursor()
  13. for i in range(0, len(infodata)):  #
  14.     data_each = []
  15.     data_each = infodata[i]
  16.     print(data_each)
  17.     sql = "insert into table_basic_info values {}".format(tuple(data_each))
  18.     try:
  19.         cursor.execute(sql)
  20.         db.commit()
  21.         print(i)
  22.     except:
  23.         db.rollback()

  24. db.close  # 关闭数据库连接
複製代碼


分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 轉播轉播 分享分享 分享淘帖
回復

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|Archiver|手機版|艾歐踢創新工坊    

GMT+8, 2024-5-15 22:56 , Processed in 0.247656 second(s), 21 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表