简体   繁体   English

使用openpyxl在excel工作表中打印python数据帧时如何跳过默认数据帧索引

[英]How to skip the default data frame index, when printing a python data frame in an excel worksheet, using openpyxl

I am trying to print a pandas data frame in an excel sheet, using openpyxl.我正在尝试使用 openpyxl 在 excel 表中打印 pandas 数据框。 Until now I have accomplished to print the data frame with the default index.到目前为止,我已经完成了使用默认索引打印数据框。 My question is, how to print it without the default index.我的问题是,如何在没有默认索引的情况下打印它。 The following example script generates Table 1 and I would like to know what I need to modify in order to come up with Table 2 .以下示例脚本生成表 1 ,我想知道我需要修改什么才能得出表 2

import pandas as pd
from openpyxl.utils.dataframe import dataframe_to_rows

df = pd.DataFrame((1,2,3,4,5,6))
wb = openpyxl.Workbook()           
sheet = wb.active 
rows = dataframe_to_rows(df)

for r_idx, row in enumerate(rows, 1):
    for c_idx, value in enumerate(row, 1):
         sheet.cell(row=r_idx+1, column=c_idx, value=value)

wb.save('book1.xlsx')

Table 1表格1

  0

0 1
1 2
2 3
3 4
4 5
5 6

Table 2表 2

1
2
3
4
5
6

Unless you have a more elaborated requirement, it's quite easier to go straight with pandas.DataFrame.to_excel , which already integrates with openpyxl .除非您有更详细的要求,否则 go 直接使用pandas.DataFrame.to_excel更容易,它已经与openpyxl集成

df.to_excel('book1.xlsx')

To drop the index, just add:要删除索引,只需添加:

df.to_excel('book1.xlsx', index=False)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 excel 的一个单元格中插入 pandas 数据帧(使用 openpyxl),其中的值将用逗号分隔? - How to insert a pandas data frame in one cell in excel (using openpyxl), where the values will be separated with comma? 使用Python使用数据框名称作为文件名将数据框写入excel - Write data frame to excel with the data frame name as filename using Python 在Python中使用win32com将数据框写入工作表 - Write a data frame to worksheet using win32com in Python python - 如何为数据框分配特殊索引? - python - how to assign a special index to the data frame? 如何将工作表转换为 Pandas 中的数据框? - How to convert a worksheet to a Data frame in Pandas? 将pd数据框填入现有Excel工作表(使用openpyxl v2.3.2) - Fill in pd data frame into existing excel sheet (using openpyxl v2.3.2) 无法使用openpyxl将数据附加到Excel文件中的工作表中 - Unable to append data to a worksheet in an excel file using openpyxl 通过xlwings将数据从pandas中的数据帧写入Excel时如何跳过默认索引(左侧的系列列)? - How to skip default index (series column on the left) when writing data from dataframe in pandas into Excel through xlwings? Openpyxl - 如何将数据范围从 Excel 工作表复制到另一个 - Openpyxl - How to copy data range from an excel worksheet to another python使用索引从组合数据框中选择单个数据框数据 - python selecting an individual data frame data from a combined data frame using index
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM