现在我回到了 pandas 数据帧数据透视表的导出主题,我找到了一个更好的导出库。打开pyxl!使用 openpyxl 可以打开预定义的 excel 模板,将数据帧数据写入预定义的漂亮表头下方,这样就不需要处理不必要的 xlsxwriter 错误。这是openpyxl中的示例代码:
import openpyxl
from openpyxl import load_workbook
workbook.active = 0
worksheet = workbook.active
worksheet.title = 'XYZ'
#check length of df
depth_df_2 = len(merged_plz_all)
#call special method to comfortably write the dataframe below your
#predefined header
update_range(workbook.active,merged_plz_all,cell_range =
'A18:'+str(spaltenindex[len(merged_plz_all.columns)])+str(depth_df_2+17))
workbook.save('yourNicelyLookingPivotTable.xlsx')
这是我在另一个 stackoverflow 线程中找到的必需的 update_range 方法。不幸的是,我没有为它添加书签,所以我请求原谅我没有提供 update_range 方法的来源。我个人觉得这个方法应该是库 openpyxl 本身的一部分!
def update_range(worksheet, data, cell_range=None, named_range=None):
"""
Updates an excel worksheet with the given data.
:param worksheet: an excel worksheet
:param data: data used to update the worksheet cell range (list, tuple, np.ndarray, pd.Dataframe)
:param cell_range: a string representing the cell range, e.g. 'AB12:XX23'
:param named_range: a string representing an excel named range
"""
def clean_data(data):
if not isinstance(data, (list, tuple, np.ndarray, pd.DataFrame)):
raise TypeError('Invalid data, data should be an array type iterable.')
if not len(data):
raise ValueError('You need to provide data to update the cells')
if isinstance(data, pd.DataFrame):
data = data.values
elif isinstance(data, (list, tuple)):
data = np.array(data)
return np.hstack(data)
def clean_cells(worksheet, cell_range, named_range):
# check that we can access a cell range
if not any((cell_range, named_range) or all((cell_range, named_range))):
raise ValueError('`cell_range` or `named_range` should be provided.')
# get the cell range
if cell_range:
try:
cells = np.hstack(worksheet[cell_range])
except (CellCoordinatesException, AttributeError):
raise ValueError('The cell range provided is invalid, cell range must be in the form XX--[:YY--]')
else:
try:
cells = worksheet.get_named_range(named_range)
except (TypeError):
raise ValueError('The current worksheet {} does not contain any named range {}.'.format(
worksheet.title,
named_range))
# checking that we have cells to update, and data
if not len(cells):
raise ValueError('You need to provide cells to update.')
return cells
cells = clean_cells(worksheet, cell_range, named_range)
data = clean_data(data)
# check that the data has the same dimension as cells
if len(cells) != data.size:
raise ValueError('Cells({}) should have the same dimension as the data({}).'.format(len(cells), data.size))
for i, cell in enumerate(cells):
cell.value = data[i]