【发布时间】:2018-09-06 20:04:05
【问题描述】:
我是 Python 新手,需要一些帮助。
我正在使用 Python 3.6.1。我正在创建一个 Python 脚本,该脚本将从文件夹中读取所有 Excel (.xlsx) 文件。在这些文件中,它应该搜索包含 SQL 选项卡作为工作表的文件,然后它应该从工作表的 SQL 选项卡复制 A2 列,并创建一个与附加到它的 Excel 文件同名的 .sql。 到目前为止,我能够从文件夹中读取所有 .xlsx 文件,查看它们是否有 SQL 选项卡,然后复制 A2 列。有人可以帮助我指导如何创建 .sql 文件并将所有 Excel 文件的 sql 复制到这些 .sql 文件中,并将 Excel 名称附加到 .sql 文件中。
以下是我现在的位置,
import os
import pandas as pd
from os import walk
from openpyxl import load_workbook
cpt = sum([len(files) for r, d, files in os.walk(r"C:\Users\Data_Dumps\New folder")])
for dirpath, dirnames, filenames in walk(r'C:\Users\Data_Dumps\New folder'):
print('Total Files in the folder are: %d' %cpt)
print('Total filenames are')
print(filenames)
files = os.listdir(dirpath)
print(files)
files_xls = [f for f in filenames if f[-4:] == 'xlsx']
print('Excel files are:')
print(files_xls)
#Creating data frame to store SQL
df = pd.DataFrame()
files_xls_string = '\n'.join(files_xls)
df = df.append(files_xls_string)
wb = load_workbook(files_xls_string, read_only=True)
if 'SQL' in wb.sheetnames:
sheet = wb.get_sheet_by_name('SQL')
SQL = sheet['A2'].value
@Shams 的注意事项:这是一条 SQL SELECT 语句,您的数据在哪里?
A2 值 eg:
select ip.item_code , ip.gla_code_ar ,r.ruleit_text LCSPAINTSZ from item i , itemplant ip , ruleit r where i.item_code = ip.item_code and ip.plant_code = '14' and i.item_active = 1 --and i.item_code = '457332' and i.item_code = r.item_code and r.urule_code = 'LCSPAINTSZ'
【问题讨论】:
-
您能提供打印输出
sheet['A2'].value是什么吗?最好用不同于 SQL 的方式调用它,它通常保留为常量。也通过说 SQL - 你的意思是 A2 列中有一些符合 SQL 条件的文本?理解 Excel 文件中的内容有点令人困惑。 -
Sure SQL 选项卡实际上包含我想从 A2 值中提取的 SQL,例如:select ip.item_code 、 ip.gla_code_ar 、r.ruleit_text LCSPAINTSZ from item i 、 itemplant ip 、 ruleit r where i。 item_code = ip.item_code and ip.plant_code = '14' and i.item_active = 1 --and i.item_code = '457332' and i.item_code = r.item_code and r.urule_code = 'LCSPAINTSZ' 我想提取从 A2 值中提取 sql 并将其放入 .sql 文件中,并附加 excel 文件名。
-
所以 A2 值是字符串,你只需要将它写入文件。很简单,很快就会给出答案
标签: python sql python-3.x