python pandas读取csv表格写入word

15 篇文章 0 订阅
4 篇文章 0 订阅

1.安装

pip install python-docx

2.代码

import pandas as pd
from docx import Document 
from docx.shared import Pt # 设置字号
from docx.shared import Cm # 设置宽度

document = Document() #创建表格实例
document.add_heading('标题', level=1)  #添加标题

df = pd.read_csv("docx_excel_test.csv",encoding='gbk') #encoding 默认uft-8

row = df.shape[0] + 1 # 行数,加标题栏
col = df.shape[1] # 列数

#设置表格样式
table = document.add_table(rows=row, cols=col, style = "Light Shading") #三线表格式

#写入列标签
for i in range(1,col):
    table.cell(0,i).text = str(list(df.columns)[i])

#针对行列索引为字符,表格数据为numpy格式
for i in range(1, row):
    for j in range(col):
        cell = table.cell(i,j)
        if str(type(df.iloc[i-1,j])) == "<class 'str'>":
            table.cell(i-1,j).width = Cm(4) #设置行索引格式
            cell.text = str(df.iloc[i-1,j]) #写入行索引
            
        if str(type(df.iloc[i-1,j]))  ==  "<class 'numpy.float64'>":
            cell.text = '%.2f'%(df.iloc[i-1,j]) #写入设置数值的保留小数

table.autofit = True #表格自动适应窗口大小
table.style.font.name = u'楷体' #设置字体格式
table.style.font.size = Pt(12)  #设置字体大小

document.save("test.docx")

3.结果
在这里插入图片描述
测试数据
链接:https://pan.baidu.com/s/1aUBS7P0eJQxM7X5xeqkuoQ
提取码:7zdy

更多表格样式

https://blog.csdn.net/xtfge0915/article/details/83480120

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值