我正在用python创建Django动态Excel文件,该文件已下载(未存储在本地),我需要使工作表从右向左显示,而不是从左向右显示。
这是我使用的代码:
import pandas
from io import BytesIO, StringIO
sio = BytesIO()
PandasDataFrame = pandas.DataFrame([['t1', 't2'], ['t3', 't4']], index = ['t1', 't2'], columns = ['t11', 't1'] )
PandasWriter = pandas.ExcelWriter(sio, engine='xlsxwriter')
PandasDataFrame.to_excel(PandasWriter, sheet_name='Sheet1')
PandasWriter.book.add_format({'reading_order': 2})
PandasWriter.save()
PandasWriter.close()
sio.seek(0)
workbook = sio.read()
response = HttpResponse(workbook,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
response['Content-Disposition'] = 'attachment; filename=wrong_data.xlsx'
return (response)
答案 0 :(得分:1)
这是一个简单的Pandas示例,演示了如何更改文本以及工作表方向。您可以自己将其转换为Django示例。
# _*_ coding: utf-8
import pandas as pd
# Create a Pandas dataframe from some data.
df = pd.DataFrame({'Data': [u'نص عربي / English text'] * 6})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter('pandas_simple.xlsx', engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Add the cell formats.
format_right_to_left = workbook.add_format({'reading_order': 2})
# Change the direction for the worksheet.
worksheet.right_to_left()
# Make the column wider for visibility and add the reading order format.
worksheet.set_column('B:B', 30, format_right_to_left)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
有关更多详细信息,请参见the worksheet right_to_left()方法上的XlsxWriter文档。