使用openpyxl进行数据验证并不是写入文件 - 附带的代码

时间:2017-02-17 15:51:14

标签: python validation openpyxl

实际编写每个文件的代码运行良好。我遇到的问题是数据验证件似乎没有做任何事情。在我参考的范围内没有创建下拉。

提前感谢您提供任何帮助!

%%time

import pandas as pd
import xlsxwriter as ew
import csv as csv
import os
import glob
import openpyxl

#remove existing files from directory
files = glob.glob(#filename)
for f in files:
    os.remove(f)

pendpath = #filename
df = pd.read_sas(pendpath)

allusers = df.UserID_NB.unique()
listuserpath = #filename
listusers = pd.read_csv(listuserpath)

listusers = listusers['USER_ID'].apply(lambda x: str(x).strip())

for id in listusers:
    x = df.loc[df['UserID_NB']==id]
    path = #filename
    x.to_excel(path, sheet_name = str(id), index = False)

    from openpyxl import load_workbook

    wb = openpyxl.load_workbook(filename = path)
    sheet = wb.get_sheet_by_name(str(id))
    maxrow = sheet.max_row    

    from openpyxl.worksheet.datavalidation import DataValidation

    dv = DataValidation(type="list", formula1='"Yes,No"', allow_blank=False, showDropDown = True)
    rangevar = 'R1:T'+ str(maxrow)
    dv.ranges.append(rangevar)
    wb.save(path)
    print str(id), rangevar

基本表格代码

 import openpyxl 

 wb = openpyxl.Workbook()
 ws = wb.active
 sheet.title = 'testsheet'

path = '#filepath'
from openpyxl.worksheet.datavalidation import DataValidation

dv = DataValidation(type="list", formula1='"Yes,No"', allow_blank=False, showDropDown = True)
dv.ranges.append('A1')
wb.save(path)

1 个答案:

答案 0 :(得分:3)

**您缺少将dv添加到worksheet

>>> # Add the data-validation object to the worksheet
>>> ws.add_data_validation(dv)

Reread the docs validation