我在 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)
Run Code Online (Sandbox Code Playgroud)
这是一个简单的 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()
Run Code Online (Sandbox Code Playgroud)
输出:
有关更多详细信息,请参阅工作表 right_to_left()方法上的 XlsxWriter 文档。
| 归档时间: |
|
| 查看次数: |
688 次 |
| 最近记录: |