python如何解析excel文件,如何使用Python直接从服务器读取Excel文件

Scenario: I am trying to read a excel file from a server folder and after that read each worksheet of that file into a dataframe and perform some operations.

Issue: I have trying multiple approaches but facing different situations: either I read the file, but it is seen as a str and the operations cannot be performed, or the file is not read.

What I tried so far:

#first attempt

os.path(r'\\X\str\Db\C\Source\selection\Date\Test','r')

#second attempt

directory = os.getcwd() + "\\C\\Source\\selection\\Date\\Test"

#third attempt

f = os.getcwd() + "\\C\\Source\\selection\\Date\\Test\\12.xlsx"

#fourth attempt

f = open(r'\\X\str\Db\C\Source\selection\Date\Test\12.xlsx', 'r')

db1 = pd.DataFrame()

db2 = pd.DataFrame()

db3 = pd.DataFrame()

bte = pd.DataFrame()

fnl = pd.DataFrame()

wb = load_workbook(f)

for sheet in wb.worksheets:

if sheet.title == "db1":

db1 = pd.read_excel(f, "db1")

Question: What is the proper way to achieve this?

解决方案

You need to open the file as rb mode

b = bynary file

r = only read the file

f = open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx', 'rb')

You can use pandas library that will do most of the work for you

import pandas

import pandas

f = pandas.read_excel(open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx','rb'), sheetname='Sheet 1')

# or using sheet index starting 0

f = pandas.read_excel(open('//X/str/Db/C/Source/selection/Date/Test/12.xlsx','rb'), sheetname=2)

There is a similar question here

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python读取多个Excel文件创建MySQL数据库可以分为以下几个步骤: 步骤一:安装相关的Python库 在Python读取Excel文件和将数据写入MySQL数据库需要使用两个非常重要的Python库。分别是:pandas和sqlalchemy。其中,pandas是Python数据处理库,可将Excel表格中的数据读取到pandas的DataFrame对象中,而sqlalchemy则是Python数据库连接的库,可以用于连接MySQL数据库进行操作。 步骤二:读取Excel文件 使用pandas库,从Excel文件读取表格数据并存储到pandas的DataFrame对象中。可以使用以下代码读取Excel文件: import pandas as pd df = pd.read_excel('file_name.xlsx') 其中,'file_name.xlsx'是所要读取Excel文件的名称。 步骤三:连接MySQL数据库 使用sqlalchemy库连接MySQL数据库。连接MySQL数据库需要填写MySQL数据库的相关参数,例如:数据库名称、服务器地址、用户名、密码等。可以使用以下代码连接MySQL数据库: from sqlalchemy import create_engine engine = create_engine('mysql+pymysql://user:password@host/db_name') 其中,'user'和'password'分别为MySQL数据库的用户名和密码,'host'为服务器地址,'db_name'为数据库名称。将以上参数填写完整后可以成功连接MySQL数据库。 步骤四:将数据写入MySQL数据库 使用to_sql()方法将Pandas DataFrame对象中的数据写入MySQL数据库。可以使用以下代码将数据写入MySQL数据库: df.to_sql('table_name', engine, if_exists='replace') 其中,'table_name'为所要创建的数据表名称,'engine'为已经连接的MySQL数据库引擎,'if_exists'为经常使用的参数,当为'replace'时,将在数据库中创建一个新的数据表并替换原始的数据表,'if_exists'的默认值为'fail',当数据库中已经存在该表名时会报错。 综上所述,以上4个步骤就是Python读取多个Excel文件创建MySQL数据库的全部流程,通过Python的强大数据处理和数据库连接能力,可以高效地完成数据的处理和存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值