从Excel表格中选择单元格Python

xyhw6mcr  于 2023-04-13  发布在  Python
关注(0)|答案(2)|浏览(159)

我有一个Excel表格,其中包含:
| ID产品|2019 - 01 - 21 10:00:00|2022年1月16日|2022年12月2日|2023年3月14日|
| --------------|--------------|--------------|--------------|--------------|
| A|四|1|二|五|
| B|六|1|三||
| C||七||六|
在同一张表中,我有一个下拉列表,其中包含(年和月)

  • 如果我在下拉列表中选择例如year = 2020和month= 1,

它将返回如下内容:
| ID产品|2019 - 01 - 21 10:00:00|
| --------------|--------------|
| A|四|
| B|六|
| C||
然后它将计算单元的SOM:在这种情况下,som = 10
下面是我的代码:

# import load_workbook
import pandas as pd
import numpy as np
from openpyxl import load_workbook
from openpyxl.worksheet.datavalidation import DataValidation
from openpyxl import Workbook
from openpyxl.styles import PatternFill

# set file path
filepath= r'test.xlsx'

wb=load_workbook(filepath)
ws=wb["sheet1"]

#Generates 10 year in the Column MK;
for number in range(1,10): 
    ws['MK{}'.format(number)].value= "202{}".format(number)
    
data_val = DataValidation(type="list",formula1='=MK1:MK10') 
ws.add_data_validation(data_val)

# drop down list with all the values from the column MK
data_val.add(ws["E2"]) 

#Generates the numbers of month in the Column MN;
for numbers in range(1,12): 
    ws['MN{}'.format(numbers)].value= "{}".format(numbers)
    

data_vals = DataValidation(type="list",formula1='=MN1:MN14') 
ws.add_data_validation(data_vals)

# drop down list with all the values from the sheet list column MK
data_vals.add(ws["E3"]) 
      
# add a color to the cell 'year' and 'month'
ws['E2'].fill = PatternFill(start_color='FFFFFF00', end_color='FFFFFF00', fill_type = 'solid')
ws['E3'].fill = PatternFill(start_color='FFFFFF00', end_color='FFFFFF00', fill_type = 'solid')

# save workbook
wb.save(filepath)

有什么建议吗?
谢谢您的帮助。

44u64gxh

44u64gxh1#

假设你的excel文件看起来像下面这样:

最终代码如下所示:

import xlrd
file = r'C:\path\test_exl.xlsx'
sheetname='Sheet1'
n=2
df = pd.read_excel(file,skiprows=[*range(2)],index_col=[0])

workbook = xlrd.open_workbook(file)
worksheet = workbook.sheet_by_name(sheetname)
year = worksheet.cell(0,0).value
month = worksheet.cell(1,0).value

datetime_cols= pd.to_datetime(df.columns,dayfirst=True,errors='coerce')
out = (df.loc[:,(datetime_cols.year == year) & (datetime_cols.month == month)]
       .reset_index())
print(out)

  ID Product  03-01-2021
0          A         4.0
1          B         6.0
2          C         NaN

明细:

你可以先使用pd.read_excel读取pandas中的表:

file = r'C:\path\test_exl.xlsx'
sheetname='Sheet1'
n=2 #change n to how many lines to skip to read the table. 
#In the above image my dataframe starts at line 3 onwards so I put n=2

df = pd.read_excel(file,skiprows=[*range(n)],index_col=[0])

然后使用xlrd访问单元格值:

import xlrd
workbook = xlrd.open_workbook(file)
worksheet = workbook.sheet_by_name(sheetname)
year = worksheet.cell(0,0).value #A1 is 0,0
month = worksheet.cell(1,0).value #A2 is 1,0 and so on..
#print(year,month) gives 2021 and 1

然后将列转换为日期时间并过滤:

datetime_cols= pd.to_datetime(df.columns,dayfirst=True,errors='coerce')
out = (df.loc[:,(datetime_cols.year == year) & (datetime_cols.month == month)]
      .reset_index())
c2e8gylq

c2e8gylq2#

不适用于python.3.10第170行,在open_workbook中引发XLRDError(FILE_FORMAT_DESCRIPTIONS[file_format]+';不支持')

相关问题