读取csv文件并将数据框写入Excel,同时对文本进行换行处理。

4
我想要得到以下输出。所有的行和列都是自动换行的,除了表头:

Excel screenshot

import pandas as pd
    import pandas.io.formats.style
    import os
    from pandas import ExcelWriter
    import numpy as np

    from xlsxwriter.utility import xl_rowcol_to_cell
    writer = pd.ExcelWriter('test1.xlsx',engine='xlsxwriter',options={'strings_to_numbers': True},date_format='mmmm dd yyyy')  
    df = pd.read_csv("D:\\Users\\u700216\\Desktop\\Reports\\CD_Counts.csv")
    df.to_excel(writer,sheet_name='Sheet1',startrow=1 , startcol=1, header=True, index=False, encoding='utf8')  
    workbook  = writer.book
    worksheet = writer.sheets['Sheet1']

    format = workbook.add_format()
    format1 = workbook.add_format({'bold': True, 'align' : 'left'})
    format.set_align('Center')
    format1.set_align('Center')
    format.set_text_wrap()
    format1.set_text_wrap()
    worksheet.set_row(0, 20, format1)
    worksheet.set_column('A:Z', 30, format)
    writer.save()

除标题外,格式应用于所有行和列。我不知道为什么格式未应用于第一列(标题),或者我想手动添加列标题编号,例如0、1、2等,以便关闭标题,从而格式化所有行和列。

在上面的截图中,A1到E1没有应用文本换行,C1列有很多空格的标题。如果我手动单击换行,它会对齐,否则所有标题都不使用文本换行格式化。


我建议您编辑问题,包括来自Excel的屏幕截图,展示您希望数据呈现的样子。 - Martin Evans
由于Pandas已经对第一行中的标题单元格应用了单元格格式,因此列格式未应用于这些单元格并被覆盖。请参见此SO问题中的以下解决方法和说明:https://dev59.com/jloV5IYBdhLWcg3wGrmI。 - jmcnamara
我尝试了 pd.formats.format.header_style = None,但它抛出了错误“模块'pandas'没有属性'formats'”。 - prasi
那么你使用的Pandas版本可能旧于0.18.1。尝试使用链接答案中提到的旧版本:pd.core.format.header_style = None - jmcnamara
好的!非常感谢你 :) - prasi
1个回答

3
一些问题:
  1. Your code is correctly attempting to format the header, but when you create your file using .to_excel() you are telling it to start at row/col 1, 1. The cells though are numbered from 0, 0. So if you change to:

    df.to_excel(writer,sheet_name='Sheet1', startrow=0, startcol=0, header=True, index=False, encoding='utf8')  
    

    You will see col A and row 1 are both formatted:

    excel screenshot

    i.e. Col A is 0 and Row 1 is 0

  2. When using Pandas to write the header, it applies its own format which will overwrite the formatting you have provided. To get around this, turn off headers and get it to only write the data from row 1 onwards and write the header manually.

以下可能更加清晰易懂:
import pandas as pd
import pandas.io.formats.style
import os
from pandas import ExcelWriter
import numpy as np

from xlsxwriter.utility import xl_rowcol_to_cell

writer = pd.ExcelWriter('test1.xlsx', engine='xlsxwriter', options={'strings_to_numbers': True}, date_format='mmmm dd yyyy')  
#df = pd.read_csv("D:\\Users\\u700216\\Desktop\\Reports\\CD_Counts.csv")
df = pd.read_csv("CD_Counts.csv")
df.to_excel(writer, sheet_name='Sheet1', startrow=1 , startcol=0, header=False, index=False, encoding='utf8')  
workbook  = writer.book
worksheet = writer.sheets['Sheet1']

format_header = workbook.add_format()
format_header.set_align('center')
format_header.set_bold()
format_header.set_text_wrap()
format_header.set_border()

format_data = workbook.add_format()
format_data.set_align('center')
format_data.set_text_wrap()

worksheet.set_column('A:Z', 20, format_data)
worksheet.set_row(0, 40, format_header)

# Write the header manually
for colx, value in enumerate(df.columns.values):
    worksheet.write(0, colx, value)

writer.save()

这将给你:

来自Pandas的文本换行的标题

注意: 还可以告诉Pandas使用哪种样式,或强制它使用None,以便继承您自己的样式。唯一的缺点是这种方法所需的方法取决于正在使用的Pandas版本。此方法适用于所有版本。


列A为0,第1行为0不起作用 :( 中心对齐可以工作,但文本换行无法工作。在C1行中有一个标题,它有很多空间,但它不能换行文本 :( - prasi
我已经添加了一张截图,请查看。 - prasi
在Excel中,我得到了带有两位数字误差的文本日期!是否可能解决这个问题? - prasi
很高兴它起作用了。关于你的日期,你需要确保数据框中的格式是正确的(即不仅仅是字符串)。你可能想考虑另外提一个问题来解决这个问题。 - Martin Evans
太好了!非常感谢你的帮助 :) - prasi
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接