我尝试使用openpyxl将现有的DataFrame导出到Excel文件。
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
wb = Workbook()
ws = wb.active
for rows in dataframe_to_rows(df, index=True, header=True):
ws.append(rows)
wb.save(filename = 'test.xlsx')
这样做时,我总是在输出文件中的标题行之后出现一个空行。
我知道我可以手动删除第二行,但是没有其他方法吗?
我已经在这里尝试过-结果相同:
import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl import Workbook
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)
wb = Workbook()
ws = wb.active
rows = dataframe_to_rows(df)
for r_idx, row in enumerate(rows, 1):
for c_idx, value in enumerate(row, 1):
ws.cell(row=r_idx, column=c_idx, value=value)
wb.save(filename = 'test.xlsx')
答案 0 :(得分:1)
使索引= False:
<a class="text-danger" data-toggle="tooltip" data-placement="top" title="Delete" (click)="openDeleteModal(deleteTemplate, smt.SMTNumber)"><i class="fa fa-trash"></i>Delete</a>
...
<ng-template #deleteTemplate>
<div class="modal-body text-center">
<p>Are you sure you want to delete this SAT?</p>
<button type="button" class="btn btn-default" (click)="confirmDelete()" >Yes</button>
<button type="button" class="btn btn-primary" (click)="denyDelete()" >No</button>
</div>
</ng-template>
答案 1 :(得分:0)
我有同样的问题。但是,我想保持index = true。 所以我只是删除了循环后的第二行
for rows in dataframe_to_rows(df, index=True, header=True):
ws.append(rows)
ws.delete_rows(2)
这对我有用
答案 2 :(得分:0)
您可以将索引设置为列,然后使用index = False
match (q.lastname, q.posting_time, q.service_time) with
| AppointmentOnly(name, postedTime) -> AppointmentOnly(name, postedTime)
| WalkIn(name, serviceTime) -> WalkIn(name, serviceTime)
| Kept(name, postedTime, serviceTime) -> Kept(name, postedTime, serviceTime)
| Open -> Open
excel文件的输出将为
答案 3 :(得分:0)
使用Openpyxl 3.0.7,您可以直接使用dataframe_to_rows 作为生成器并传递带有索引重置的数据帧,如下所示,因此您的数据帧不会更改:
def write_to_sheet(df, ws):
for r in dataframe_to_rows(df.reset_index(level=0), index=False, header=True):
ws.append(r)
for cell in ws['A'] + ws[1]:
cell.style = 'Pandas'