https://docs.microsoft.com/en-us/power-bi/service-admin-troubleshoot-excel-workbook-data
10161 次
4 回答
20
这是使用 XlsxWriter 的一种方法:
import pandas as pd
# Create a Pandas dataframe from some data.
data = [10, 20, 30, 40, 50, 60, 70, 80]
df = pd.DataFrame({'Rank': data,
'Country': data,
'Population': data,
'Data1': data,
'Data2': data})
# Create a Pandas Excel writer using XlsxWriter as the engine.
writer = pd.ExcelWriter("pandas_table.xlsx", engine='xlsxwriter')
# Convert the dataframe to an XlsxWriter Excel object. Turn off the default
# header and index and skip one row to allow us to insert a user defined
# header.
df.to_excel(writer, sheet_name='Sheet1', startrow=1, header=False, index=False)
# Get the xlsxwriter workbook and worksheet objects.
workbook = writer.book
worksheet = writer.sheets['Sheet1']
# Get the dimensions of the dataframe.
(max_row, max_col) = df.shape
# Create a list of column headers, to use in add_table().
column_settings = []
for header in df.columns:
column_settings.append({'header': header})
# Add the table.
worksheet.add_table(0, 0, max_row, max_col - 1, {'columns': column_settings})
# Make the columns wider for clarity.
worksheet.set_column(0, max_col - 1, 12)
# Close the Pandas Excel writer and output the Excel file.
writer.save()
输出:
更新:我在 XlsxWriter 文档中添加了一个类似的示例:示例:带有工作表的 Pandas Excel 输出
于 2020-08-10T19:54:51.420 回答
5
你不能用to_excel
. 一种解决方法是打开生成的 xlsx 文件并使用openpyxl添加表:
import pandas as pd
df = pd.DataFrame({'Col1': [1,2,3], 'Col2': list('abc')})
filename = 'so58326392.xlsx'
sheetname = 'mySheet'
with pd.ExcelWriter(filename) as writer:
if not df.index.name:
df.index.name = 'Index'
df.to_excel(writer, sheet_name=sheetname)
import openpyxl
wb = openpyxl.load_workbook(filename = filename)
tab = openpyxl.worksheet.table.Table(displayName="df", ref=f'A1:{chr(len(df.columns)+64)}{len(df)+1}')
wb[sheetname].add_table(tab)
wb.save(filename)
请注意,所有表头都必须是字符串。如果您有一个未命名的索引(这是规则),第一个单元格 (A1) 将为空,这会导致文件损坏。为避免这种情况,请为您的索引命名(如上所示)或使用以下方法导出没有索引的数据框:
df.to_excel(writer, sheet_name=sheetname, index=False)
于 2019-10-10T16:37:43.087 回答
4
如果您不想保存、重新打开和重新保存,另一种解决方法是使用xlsxwriter。它可以直接编写 ListObject 表,但不能直接从数据帧中编写,因此您需要拆分部分:
import pandas as pd
import xlsxwriter as xl
df = pd.DataFrame({'Col1': [1,2,3], 'Col2': list('abc')})
filename = 'output.xlsx'
sheetname = 'Table'
tablename = 'TEST'
(rows, cols) = df.shape
data = df.to_dict('split')['data']
headers = []
for col in df.columns:
headers.append({'header':col})
wb = xl.Workbook(filename)
ws = wb.add_worksheet()
ws.add_table(0, 0, rows, cols-1,
{'name': tablename
,'data': data
,'columns': headers})
wb.close()
该add_table()
函数需要'data'
一个列表列表,其中每个子列表表示数据帧的一行,并'columns'
作为标题的字典列表,其中每列由形式的字典指定{'header': 'ColumnName'}
。
于 2020-08-10T19:17:18.160 回答
1
我创建了一个包来从 pandas 编写格式正确的 excel 表:pandas-xlsx-tables
from pandas_xlsx_tables import df_to_xlsx_table
import pandas as pd
data = [10, 20, 30, 40, 50, 60, 70, 80]
df = pd.DataFrame({'Rank': data,
'Country': data,
'Population': data,
'Strings': [f"n{n}" for n in data],
'Datetimes': [pd.Timestamp.now() for _ in range(len(data))]})
df_to_xlsx_table(df, "my_table", index=False, header_orientation="diagonal")
你也可以做相反的事情xlsx_table_to_df
于 2021-10-22T19:05:52.177 回答