本文整理汇总了Python中openpyxl.load_workbook方法的典型用法代码示例。如果您正苦于以下问题:Python openpyxl.load_workbook方法的具体用法?Python openpyxl.load_workbook怎么用?Python openpyxl.load_workbook使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类openpyxl
的用法示例。
在下文中一共展示了openpyxl.load_workbook方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: parse_file
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def parse_file(filename, stream):
if filename.endswith('.tsv') or filename.endswith('.fam') or filename.endswith('.ped'):
return [[s.strip().strip('"') for s in line.rstrip('\n').split('\t')] for line in stream]
elif filename.endswith('.csv'):
return [row for row in csv.reader(stream)]
elif filename.endswith('.xls') or filename.endswith('.xlsx'):
wb = xl.load_workbook(stream, read_only=True)
ws = wb[wb.sheetnames[0]]
rows = [[_parse_excel_string_cell(cell) for cell in row] for row in ws.iter_rows()]
# trim trailing empty rows
last_row_index = max(i for i, row in enumerate(rows) if any(val for val in row))
rows = rows[:last_row_index+1]
# all rows should have same column count
last_col_index = max(max(i for i, val in enumerate(row) if val) for row in rows)
padding = [''] * last_col_index
rows = [(row + padding)[:last_col_index+1] for row in rows]
return rows
elif filename.endswith('.json'):
return json.loads(stream.read())
raise ValueError("Unexpected file type: {}".format(filename))
示例2: test_write_append_mode
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def test_write_append_mode(self, merge_cells, ext, engine, mode, expected):
import openpyxl
df = DataFrame([1], columns=['baz'])
with ensure_clean(ext) as f:
wb = openpyxl.Workbook()
wb.worksheets[0].title = 'foo'
wb.worksheets[0]['A1'].value = 'foo'
wb.create_sheet('bar')
wb.worksheets[1]['A1'].value = 'bar'
wb.save(f)
writer = ExcelWriter(f, engine=engine, mode=mode)
df.to_excel(writer, sheet_name='baz', index=False)
writer.save()
wb2 = openpyxl.load_workbook(f)
result = [sheet.title for sheet in wb2.worksheets]
assert result == expected
for index, cell_value in enumerate(expected):
assert wb2.worksheets[index]['A1'].value == cell_value
示例3: __init__
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def __init__(self, path, engine=None, mode='w', **engine_kwargs):
# Use the openpyxl module as the Excel writer.
from openpyxl.workbook import Workbook
super(_OpenpyxlWriter, self).__init__(path, mode=mode, **engine_kwargs)
if self.mode == 'a': # Load from existing workbook
from openpyxl import load_workbook
book = load_workbook(self.path)
self.book = book
else:
# Create workbook object with default optimized_write=True.
self.book = Workbook()
if self.book.worksheets:
try:
self.book.remove(self.book.worksheets[0])
except AttributeError:
# compat - for openpyxl <= 2.4
self.book.remove_sheet(self.book.worksheets[0])
示例4: __init__
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def __init__(self, output=None, **kwargs):
super(XLSRenderer, self).__init__(**kwargs)
# Make a single delegate text renderer for reuse. Most of the time we
# will just replicate the output from the TextRenderer inside the
# spreadsheet cell.
self.delegate_text_renderer = text.TextRenderer(session=self.session)
self.output = output or self.session.GetParameter("output")
# If no output filename was give, just make a name based on the time
# stamp.
if self.output == None:
self.output = "%s.xls" % time.ctime()
try:
self.wb = openpyxl.load_workbook(self.output)
self.current_ws = self.wb.create_sheet()
except IOError:
self.wb = openpyxl.Workbook()
self.current_ws = self.wb.active
示例5: __init__
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def __init__(self, file=None, template_styles=None, timestamp=None, templated_sheets=None, keep_vba=False,
data_only=False, keep_links=True):
super(TemplatedWorkbook, self).__init__()
self.workbook = load_workbook(
filename=file,
data_only=data_only,
keep_vba=keep_vba,
keep_links=keep_links
) if file else Workbook()
self.template_styles = template_styles or DefaultStyleSet()
self.timestamp = timestamp
self.templated_sheets = []
for sheetname, templated_sheet in self._items.items():
self.add_templated_sheet(templated_sheet, sheetname=sheetname, add_to_self=False)
for templated_sheet in templated_sheets or []:
self.add_templated_sheet(sheet=templated_sheet, sheetname=templated_sheet.sheetname, add_to_self=True)
self._validate()
示例6: test_xls_export_works_with_unicode
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def test_xls_export_works_with_unicode(self):
survey = create_survey_from_xls(_logger_fixture_path(
'childrens_survey_unicode.xls'))
export_builder = ExportBuilder()
export_builder.set_survey(survey)
temp_xls_file = NamedTemporaryFile(suffix='.xlsx')
export_builder.to_xls_export(temp_xls_file.name, self.data_utf8)
temp_xls_file.seek(0)
# check that values for red\u2019s and blue\u2019s are set to true
wb = load_workbook(temp_xls_file.name)
children_sheet = wb.get_sheet_by_name("children.info")
data = dict([(r[0].value, r[1].value) for r in children_sheet.columns])
self.assertTrue(data[u'children.info/fav_colors/red\u2019s'])
self.assertTrue(data[u'children.info/fav_colors/blue\u2019s'])
self.assertFalse(data[u'children.info/fav_colors/pink\u2019s'])
temp_xls_file.close()
示例7: test_to_xls_export_respects_custom_field_delimiter
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def test_to_xls_export_respects_custom_field_delimiter(self):
survey = self._create_childrens_survey()
export_builder = ExportBuilder()
export_builder.GROUP_DELIMITER = ExportBuilder.GROUP_DELIMITER_DOT
export_builder.set_survey(survey)
xls_file = NamedTemporaryFile(suffix='.xls')
filename = xls_file.name
export_builder.to_xls_export(filename, self.data)
xls_file.seek(0)
wb = load_workbook(filename)
# check header columns
main_sheet = wb.get_sheet_by_name('childrens_survey')
expected_column_headers = [
u'name', u'age', u'geo.geolocation', u'geo._geolocation_latitude',
u'geo._geolocation_longitude', u'geo._geolocation_altitude',
u'geo._geolocation_precision', u'tel.tel.office',
u'tel.tel.mobile', u'_id', u'meta.instanceID', u'_uuid',
u'_submission_time', u'_index', u'_parent_index',
u'_parent_table_name', u'_tags', '_notes']
column_headers = [c[0].value for c in main_sheet.columns]
self.assertEqual(sorted(column_headers),
sorted(expected_column_headers))
xls_file.close()
示例8: test_to_xls_export_generates_valid_sheet_names
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def test_to_xls_export_generates_valid_sheet_names(self):
survey = create_survey_from_xls(_logger_fixture_path(
'childrens_survey_with_a_very_long_name.xls'))
export_builder = ExportBuilder()
export_builder.set_survey(survey)
xls_file = NamedTemporaryFile(suffix='.xls')
filename = xls_file.name
export_builder.to_xls_export(filename, self.data)
xls_file.seek(0)
wb = load_workbook(filename)
# check that we have childrens_survey, children, children_cartoons
# and children_cartoons_characters sheets
expected_sheet_names = ['childrens_survey_with_a_very_lo',
'childrens_survey_with_a_very_l1',
'childrens_survey_with_a_very_l2',
'childrens_survey_with_a_very_l3']
self.assertEqual(wb.get_sheet_names(), expected_sheet_names)
xls_file.close()
示例9: test_child_record_parent_table_is_updated_when_sheet_is_renamed
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def test_child_record_parent_table_is_updated_when_sheet_is_renamed(self):
survey = create_survey_from_xls(_logger_fixture_path(
'childrens_survey_with_a_very_long_name.xls'))
export_builder = ExportBuilder()
export_builder.set_survey(survey)
xls_file = NamedTemporaryFile(suffix='.xlsx')
filename = xls_file.name
export_builder.to_xls_export(filename, self.long_survey_data)
xls_file.seek(0)
wb = load_workbook(filename)
# get the children's sheet
ws1 = wb.get_sheet_by_name('childrens_survey_with_a_very_l1')
# parent_table is in cell K2
parent_table_name = ws1.cell('K2').value
expected_parent_table_name = 'childrens_survey_with_a_very_lo'
self.assertEqual(parent_table_name, expected_parent_table_name)
# get cartoons sheet
ws2 = wb.get_sheet_by_name('childrens_survey_with_a_very_l2')
parent_table_name = ws2.cell('G2').value
expected_parent_table_name = 'childrens_survey_with_a_very_l1'
self.assertEqual(parent_table_name, expected_parent_table_name)
xls_file.close()
示例10: write_xlsx
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def write_xlsx(vulnerabilities):
print(define.GREEN+"[*]内容正在写入 vu_name:%s"%vulnerabilities['vt_name'])
wb = ws.load_workbook(define.filename)
sheet1 = wb['Sheet']
num = sheet1.max_row
sheet1.cell(row = num+1,column = 1,value = vulnerabilities['host'])
sheet1.cell(row = num+1,column = 2,value = vulnerabilities['vt_name'])
sheet1.cell(row = num+1,column = 3,value = vulnerabilities['severity'])
sheet1.cell(row = num+1,column = 4,value = vulnerabilities['affects_detail'])
sheet1.cell(row = num+1,column = 5,value = vulnerabilities['affects_url'])
sheet1.cell(row = num+1,column = 6,value = vulnerabilities['request'])
sheet1.cell(row = num+1,column = 7,value = vulnerabilities['recommendation'])
sheet1.cell(row = num+1,column = 8,value = vulnerabilities['description'])
sheet1.cell(row = num+1,column = 9,value = vulnerabilities['details'])
wb.save(define.filename)
#文件创建
示例11: _parse_excel_to_hosts
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def _parse_excel_to_hosts(self):
wb = load_workbook(self.path)
sheet_names = wb.sheetnames
for s_name in sheet_names:
sh = wb[s_name]
rows = list(sh.rows)
for row in rows:
if row[0].row == 1:
continue
else:
defaults = {
"name": row[0].value,
"ip": row[1].value,
"port": int(row[2].value),
"credential": row[3].value
}
self.__hosts.append(defaults)
示例12: import_meta
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def import_meta():
inws = pathlib.Path('./database/datacn_datasets')
print(inws)
# for y in os.listdir(inws):
# print(y)
for cat_path in inws.iterdir():
print('x' * 40)
print(cat_path.name)
if cat_path.name.lower().endswith('.xlsx'):
print('////')
pass
else:
continue
wb = load_workbook(str(cat_path))
sheets = wb.sheetnames
for sheet in sheets:
catid = sheet.split('_')[0]
ws = wb[sheet]
rows = ws.max_row
cols= ws.max_column
for i in range(1,rows):
sig = ws.cell(row=i, column=1).value
print(sig)
if sig:
get_meta(catid, sig)
示例13: chli_xlsx
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def chli_xlsx(cat_path):
print('操作中,请等待')
result_xlsx = 'xx_{}'.format(os.path.split(str(cat_path))[-1])
wb = load_workbook(cat_path)
# uid_reg = re.compile('\_kind-\w{1}')
# kind_pat = re.search(uid_reg, str(cat_path))
# if kind_pat:
kind_sig = '9'
sheets = wb.sheetnames
for sheet in sheets:
catid = sheet.split('_')[0]
ws = wb[sheet]
rows = ws.max_row
cols = ws.max_column
for i in range(1, rows + 1):
sig = ws.cell(row=i, column=1).value
if sig:
atitle = get_meta(catid, sig, kind_sig=kind_sig)
示例14: insert_part_fields_into_xlsx
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def insert_part_fields_into_xlsx(part_fields_dict, filename, recurse, group_components, backup):
'''Insert the fields in the extracted part dictionary into an XLSX spreadsheet.'''
logger.log(
DEBUG_OVERVIEW,
'Inserting extracted fields into XLSX file {}.'.format(filename))
if backup:
create_backup(filename)
# Either insert fields into an existing workbook, or use an empty one.
try:
wb = pyxl.load_workbook(filename, data_only=True)
except IOError:
wb = None
wb = insert_part_fields_into_wb(part_fields_dict, wb)
if group_components:
wb = group_wb(wb)
wb.save(filename)
示例15: excel_to_db
# 需要导入模块: import openpyxl [as 别名]
# 或者: from openpyxl import load_workbook [as 别名]
def excel_to_db(from_excel, to_db):
'''Transfer Excel file to leveldb, return total count.'''
_wb = load_workbook(from_excel, read_only=True)
_ws = _wb.active
_db = leveldb.LevelDB(to_db, create_if_missing=True) if isinstance(to_db, str) else to_db
total = 0
for _row in _ws.iter_rows(min_row=2, min_col=1, max_col=1):
if _row and _row[0] and _row[1]:
_key, _value = '', ''
if _row[0].data_type == cell.Cell.TYPE_STRING:
_key = _row[0].value.encode('utf-8')
_key = ''.join(_key.split())
if _row[1].data_type == cell.Cell.TYPE_STRING:
_value = _row[0].value.encode('utf-8')
_value = ''.join(_value.split())
_db.Put(_key, _value)
total += 1
_wb.close()
return total