本文整理汇总了Python中xlsxwriter.Workbook方法的典型用法代码示例。如果您正苦于以下问题:Python xlsxwriter.Workbook方法的具体用法?Python xlsxwriter.Workbook怎么用?Python xlsxwriter.Workbook使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xlsxwriter
的用法示例。
在下文中一共展示了xlsxwriter.Workbook方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def __init__(self, path, engine=None, encoding=None, mode='w',
**engine_kwargs):
# Use the xlwt module as the Excel writer.
import xlwt
engine_kwargs['engine'] = engine
if mode == 'a':
raise ValueError('Append mode is not supported with xlwt!')
super(_XlwtWriter, self).__init__(path, mode=mode, **engine_kwargs)
if encoding is None:
encoding = 'ascii'
self.book = xlwt.Workbook(encoding=encoding)
self.fm_datetime = xlwt.easyxf(num_format_str=self.datetime_format)
self.fm_date = xlwt.easyxf(num_format_str=self.date_format)
示例2: main
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def main():
args = make_args()
config = configparser.ConfigParser()
utils.load_config(config, args.config)
for cmd in args.modify:
utils.modify_config(config, cmd)
with open(os.path.expanduser(os.path.expandvars(args.logging)), 'r') as f:
logging.config.dictConfig(yaml.load(f))
model_dir = utils.get_model_dir(config)
path, step, epoch = utils.train.load_model(model_dir)
state_dict = torch.load(path, map_location=lambda storage, loc: storage)
mapper = [(inflection.underscore(name), member()) for name, member in inspect.getmembers(importlib.machinery.SourceFileLoader('', __file__).load_module()) if inspect.isclass(member)]
path = os.path.join(model_dir, os.path.basename(os.path.splitext(__file__)[0])) + '.xlsx'
with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
worksheet = workbook.add_worksheet(args.worksheet)
for j, (key, m) in enumerate(mapper):
worksheet.write(0, j, key)
for i, (name, variable) in enumerate(state_dict.items()):
value = m(name, variable)
worksheet.write(1 + i, j, value)
if hasattr(m, 'format'):
m.format(workbook, worksheet, i, j)
worksheet.autofilter(0, 0, i, len(mapper) - 1)
worksheet.freeze_panes(1, 0)
logging.info(path)
示例3: save_xlsx
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def save_xlsx(self, df, path, worksheet='worksheet'):
with xlsxwriter.Workbook(path, {'strings_to_urls': False, 'nan_inf_to_errors': True}) as workbook:
worksheet = workbook.add_worksheet(worksheet)
for j, key in enumerate(df):
worksheet.write(0, j, key)
try:
m = self.mapper[key]
except (KeyError, AttributeError):
m = None
if hasattr(m, 'get_format'):
fmt = m.get_format(workbook, worksheet)
else:
fmt = None
for i, value in enumerate(df[key]):
worksheet.write(1 + i, j, value, fmt)
if hasattr(m, 'format'):
m.format(workbook, worksheet, i, j)
worksheet.autofilter(0, 0, i, len(self.mapper) - 1)
worksheet.freeze_panes(1, 0)
示例4: valid_excel_file_1
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def valid_excel_file_1():
file_path = "valid_underscore.xlsx"
workbook = xlsxwriter.Workbook(str(file_path))
worksheet = workbook.add_worksheet("sheet_a")
table = [
["data", "_data", "da_ta", "data_"],
[1, 0.0, "a", "aaaa"],
[2, 0.1, "b", "bbbb"],
[3, 0.2, "c", "cccc"],
]
for row_idx, row in enumerate(table):
for col_idx, item in enumerate(row):
worksheet.write(row_idx, col_idx, item)
workbook.close()
return str(file_path)
示例5: invalid_excel_file_1
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def invalid_excel_file_1():
file_path = "invalid.xlsx"
workbook = xlsxwriter.Workbook(file_path)
worksheet = workbook.add_worksheet("testsheet1")
table = [
["", "", "", ""],
["", "a", "", "c"],
["", "aa", "ab", ""],
["", "", 1.1, "a"],
]
for row_idx, row in enumerate(table):
for col_idx, item in enumerate(row):
worksheet.write(row_idx, col_idx, item)
worksheet = workbook.add_worksheet("testsheet2")
workbook.close()
return file_path
示例6: __export_to_xlsx
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def __export_to_xlsx(self):
r"""Export the results in the xlsx form.
See Also:
:func:`NiaPy.Runner.__generateExportName`
"""
self.__create_export_dir()
workbook = xlsxwriter.Workbook(self.__generate_export_name("xlsx"))
worksheet = workbook.add_worksheet()
row, col, nRuns = 0, 0, 0
for alg in self.results:
_, col = worksheet.write(row, col, alg), col + 1
for bench in self.results[alg]:
worksheet.write(row, col, bench)
nRuns = len(self.results[alg][bench])
for i in range(len(self.results[alg][bench])):
_, row = worksheet.write(row, col, self.results[alg][bench][i]), row + 1
row, col = row - len(self.results[alg][bench]), col + 1
row, col = row + 1 + nRuns, col - 1 + len(self.results[alg])
workbook.close()
logger.info("Export to XLSX completed!")
示例7: export_campaign_xlsx
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def export_campaign_xlsx(self):
"""Export the current campaign to an Excel compatible XLSX workbook."""
dialog = extras.FileChooserDialog('Export Campaign To Excel', self)
file_name = self.config['campaign_name'] + '.xlsx'
response = dialog.run_quick_save(file_name)
dialog.destroy()
if not response:
return
destination_file = response['target_path']
campaign_tab = self.tabs['campaign']
workbook = xlsxwriter.Workbook(destination_file)
title_format = workbook.add_format({'bold': True, 'size': 18})
for tab_name, tab in campaign_tab.tabs.items():
if not isinstance(tab, CampaignViewGenericTableTab):
continue
tab.export_table_to_xlsx_worksheet(workbook.add_worksheet(tab_name), title_format)
workbook.close()
示例8: translate_to
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def translate_to():
post = []
book = open_workbook(sys.argv[1])
sheet = book.sheet_by_index(0)
ctr = 0
for row in sheet.col(1):
if ctr!=0:
post.append(row.value.encode('utf-8'))
ctr+=1
for i in range(0,len(post)):
str(post[i])
translations=[]
xbook = xlsxwriter.Workbook('hinglish.xlsx')
xsheet = xbook.add_worksheet('Test')
for i in range(0,len(post)):
translation = translator.translate(post[i],src='en', dest='hi')
xsheet.write(i,1,''.join((translation.text)))
示例9: xlsx
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def xlsx():
'''Returns an xlsx file containing the entire dataset for the current
workspace.'''
sfp = BytesIO()
with xlsxwriter.Workbook(sfp) as workbook:
# create a worksheet for each table in the current workspace
for table in recon.get_tables():
rows = recon.query(f"SELECT * FROM {table}", include_header=True)
columns = rows.pop(0)
rows = columnize(columns, rows)
add_worksheet(workbook, table, rows)
sfp.seek(0)
return send_file(
sfp,
mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
as_attachment=True,
attachment_filename=f"{current_app.config['WORKSPACE']}.xlsx"
)
示例10: __init__
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def __init__(self, path, engine=None, **engine_kwargs):
# Use the openpyxl module as the Excel writer.
from openpyxl.workbook import Workbook
super(_OpenpyxlWriter, self).__init__(path, **engine_kwargs)
# Create workbook object with default optimized_write=True.
self.book = Workbook()
# Openpyxl 1.6.1 adds a dummy sheet. We remove it.
if self.book.worksheets:
try:
self.book.remove(self.book.worksheets[0])
except AttributeError:
# compat
self.book.remove_sheet(self.book.worksheets[0])
示例11: __init__
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def __init__(self, output_filename="output.xlsx"):
""" Generate XLSX """
self.workbook = xlsxwriter.Workbook(output_filename)
self.core_worksheet = self.workbook.add_worksheet("Core")
self.core_alteration_worksheet = self.workbook.add_worksheet("Core Alteration")
self.plugins_worksheet = self.workbook.add_worksheet("Plugins")
self.plugins_vulns_worksheet = self.workbook.add_worksheet("Plugins Vulns")
self.plugins_alteration_worksheet = self.workbook.add_worksheet("Plugins Alteration")
self.themes_worksheet = self.workbook.add_worksheet("Themes")
self.themes_vulns_worksheet = self.workbook.add_worksheet("Themes Vulns")
self.themes_alteration_worksheet = self.workbook.add_worksheet("Themes Alteration")
self.generate_heading()
self.generate_formatting(self.workbook)
示例12: Open
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def Open(self):
"""Creates a new workbook.
Raises:
IOError: if the specified output file already exists.
OSError: if the specified output file already exists.
ValueError: if the filename is not set.
"""
if not self._filename:
raise ValueError('Missing filename.')
if os.path.isfile(self._filename):
raise IOError((
'Unable to use an already existing file for output '
'[{0:s}]').format(self._filename))
options = {
'constant_memory': True,
'strings_to_urls': False,
'strings_to_formulas': False,
'default_date_format': self._timestamp_format}
self._workbook = xlsxwriter.Workbook(self._filename, options)
self._sheet = self._workbook.add_worksheet('Sheet')
self._current_row = 0
示例13: transfer_and_save
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def transfer_and_save(self, json_str):
json_orders = json.loads(json_str)
for key in json_orders:
if key == 'OrderEnities':
json_order_lists = json_orders[key]
book = xlsxwriter.Workbook('ctrip_order.xlsx')
sheet = book.add_worksheet()
sheet.write(0, 0, 'Date')
sheet.write(0, 1, 'OrderDetails')
sheet.write(0, 2, 'Price')
for i in range(len(json_order_lists)):
json_order = json_order_lists[i]
sheet.write(i+1, 0, json_order['BookingDate'])
sheet.write(i+1, 1, json_order['OrderName'])
sheet.write(i+1, 2, json_order['OrderTotalPrice'])
book.close()
# download orders and save them in an excel file
示例14: transfer_and_save_bill
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import Workbook [as 别名]
def transfer_and_save_bill(self, bill_json_str):
bill_json = json.loads(bill_json_str)
bill_json_month_lists = bill_json['data']
book = xlsxwriter.Workbook('yidong_bill.xlsx')
sheet = book.add_worksheet()
sheet.write(0, 0, 'Date')
sheet.write(0, 1, 'ItemDetails')
sheet.write(0, 2, 'Price')
sheet_count = 0
for i in range(len(bill_json_month_lists)):
bill_json_month = bill_json_month_lists[i]
month = bill_json_month['billMonth']
month_item_lists = bill_json_month['billMaterials']
for j in range(len(month_item_lists)):
bill_item = month_item_lists[j]['billMaterialInfos']
if len(bill_item) != 0:
sheet_count += 1
sheet.write(sheet_count, 0, month)
sheet.write(sheet_count, 1, bill_item[0]['itemName'])
sheet.write(sheet_count, 2, bill_item[0]['itemValue'])
示例15: __init__
# 需要导入模块: import xlsxwriter [as 别名]
# 或者: from xlsxwriter import 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])