在日常工作中,Python在辦公自動化領域應用非常廣泛,如批量將多個Excel中的數據進行計算并生成圖表,批量將多個Excel按固定格式轉換成Word,或者定時生成文件并發送郵件等場景。本文主要以一個簡單的小例子,簡述Python在Excel和Word方面進行相互轉換的相關知識點,謹供學習分享使用,如有不足之處,還請指正。
相關知識點
本文主要是將Excel文件通過一定規則轉換成Word文檔,涉及知識點如下所示:
xlrd模塊:主要用于Excel文件的讀取,相關內容如下:
- xlrd.open_workbook(self.excel_file) 打開Excel文件并返回文檔對象,參數為Excel的完整路徑
- book.sheet_by_name(self.sheet_name) 通過名稱獲取對應的sheet頁,并返回sheet對象
- sheet.nrows sheet頁的有效行數
- sheet.ncols sheet頁的有效列數
- sheet.row_values(0) 返回Excel中對應sheet頁的第一行的值,以數組返回
- sheet.cell_value(row, col) 返回某一個單元格的值
python-docx模塊:主要操作Word文檔,如:表格,段落等相關,相關內容如下所示:
- Document word的文檔對象,代表整個word文檔
- doc.sections[0] 獲取章節
- doc.add_section(start_type=WD_SECTION_START.CONTINUOUS) 添加連續章節
- doc.add_heading(third, level=2) 增加標題,level表示級別,如二級標題,返回標題對象
- doc.add_paragraph(text='', style=None) 增加段落,返回段落對象
- doc.add_table(rows=4, cols=5) 增加表格,并返回表格對象
- doc_table.style = "Table Grid" 設置表格樣式
- doc_table.rows[0].cells[1].merge(doc_table.rows[0].cells[4]) 合并單元格
- doc_table.rows[3].cells 獲取表格某一行所有單元格,以數組形式返回
- head_cells[0].width = Cm(1.9) 設置列寬,單位cm
- doc_table.rows[i].cells[j].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER 表格內容垂直居中
- doc_table.add_row() 新增行,并返回行對象
插件安裝
插件可以在pycharm的terminal面板下進行安裝。python-docx安裝命令為:pip install python-docx
xlrd安裝命令為:pip install xlrd
如下所示:

數據源文件
數據源是一系列格式相同的Excel文件,共七列,其中第1列要按【/】進行截取拆分,格式如下:

核心代碼
本文核心源碼,主要分三部分:
導入相關模塊包,如下所示:
import xlrd
from docx import Document
from docx.enum.section import WD_ORIENTATION
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt, Cm, RGBColor
from docx.oxml.ns import qn
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
讀取Excel,如下所示:
def read_excel(self):
"""讀取Excel"""
book = xlrd.open_workbook(self.excel_file)
sheet = book.sheet_by_name(self.sheet_name)
nrows = sheet.nrows # 行數
ncols = sheet.ncols # 列數
datas = [] # 存放數據
# 第一列 標題
keys = sheet.row_values(0)
for row in range(1, nrows):
data = {} # 每一行數據
for col in range(0, ncols):
value = sheet.cell_value(row, col) # 取出每一個單元格的數據
# 替換到特殊字符
value = value.replace('', '').replace('>', '').replace('$', '')
data[keys[col]] = value
# 截取第一列元素
if col == 0:
first = '' # 截取元素 第1
second = '' # 截取元素 第2
third = '' # 截取元素 第3
arrs = value.lstrip('/').split('/') # 去掉第一個/ 然后再以/分組
if len(arrs) > 0:
if len(arrs) == 1:
first = arrs[0]
second = first
third = second
elif len(arrs) == 2:
first = arrs[0]
second = arrs[1]
third = second
elif len(arrs) == 3:
first = arrs[0]
second = arrs[1]
third = arrs[2]
else:
first = arrs[0]
second = arrs[1]
third = arrs[2]
else:
first = value.ltrip('/')
second = first
third = second
data['first'] = first
data['second'] = second
data['third'] = third
# 截取第一列結束
datas.append(data)
return datas
生成Word部分:
def write_word(self, datas):
"""生成word文件"""
if len(datas) 1:
print('Excel沒有內容')
return
# 定義word文檔對象
doc = Document()
# 添加橫向
section = doc.sections[0] # doc.add_section(start_type=WD_SECTION_START.CONTINUOUS) # 添加橫向頁的連續節
section.orientation = WD_ORIENTATION.LANDSCAPE
page_h, page_w = section.page_width, section.page_height
section.page_width = page_w # 設置橫向紙的寬度
section.page_height = page_h # 設置橫向紙的高度
# 設置字體
doc.styles['Normal'].font.name = u'宋體'
doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
# 獲取第3部分(部門) 并去重
data_third = []
for data in datas:
third = data['third']
if data_third.count(third) == 0:
data_third.append(third)
for third in data_third:
h2 = doc.add_heading(third, level=2) # 寫入部門,二級標題
run = h2.runs[0] # 可以通過add_run來設置文字,也可以通過數組來獲取
run.font.color.rgb = RGBColor(0, 0, 0)
run.font.name = u'宋體'
doc.add_paragraph(text='', style=None) # 增加空白行 換行
# 開始獲取模板
data_template = []
for data in datas:
if data['third'] == third:
template = {'first': data['first'], '模板名稱': data['模板名稱']}
if data_template.count(template) == 0:
data_template.append(template)
# 獲取模板完成
# 遍歷模板
for template in data_template:
h3 = doc.add_heading(template['模板名稱'], level=3) # 插入模板名稱,三級標題
run = h3.runs[0] # 可以通過add_run來設置文字,也可以通過數組來獲取
run.font.color.rgb = RGBColor(0, 0, 0)
run.font.name = u'宋體'
doc.add_paragraph(text='', style=None) # 換行
data_table = filter(
lambda data: data['third'] == third and data['模板名稱'] == template['模板名稱'] and data['first'] ==
template['first'], datas)
data_table = list(data_table)
# 新增表格 4行5列
doc_table = doc.add_table(rows=4, cols=5)
doc_table.style = "Table Grid"
doc_table.style.font.size = Pt(9)
doc_table.style.font.name = '宋體'
# 合并單元格 賦值
doc_table.rows[0].cells[1].merge(doc_table.rows[0].cells[4])
doc_table.rows[1].cells[1].merge(doc_table.rows[1].cells[4])
doc_table.rows[2].cells[1].merge(doc_table.rows[2].cells[4])
doc_table.rows[0].cells[0].text = '流程名稱:'
doc_table.rows[0].cells[1].text = data_table[0]['模板名稱']
doc_table.rows[1].cells[0].text = '使用人:'
doc_table.rows[1].cells[1].text = data_table[0]['first']
doc_table.rows[2].cells[0].text = '流程說明:'
doc_table.rows[2].cells[1].text = data_table[0]['流程說明']
# 設置標題
head_cells = doc_table.rows[3].cells # 前面還有三行,特殊處理
head_cells[0].text = '節點'
head_cells[1].text = '節點名'
head_cells[2].text = '處理人員'
head_cells[3].text = '處理方式'
head_cells[4].text = '跳轉信息'
# 設置列寬
head_cells[0].width = Cm(1.9)
head_cells[1].width = Cm(4.83)
head_cells[2].width = Cm(8.25)
head_cells[3].width = Cm(2.54)
head_cells[4].width = Cm(5.64)
# 第1 列水平居中,并設置行高,所有單元格內容垂直居中
for i in range(0, 4):
# 水平居中
p = doc_table.rows[i].cells[0].paragraphs[0]
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
doc_table.rows[i].height = Cm(0.6) # 行高
# 垂直居中
for j in range(0, 5):
doc_table.rows[i].cells[j].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
# 生成表格并填充內容
row_num = 0
for data in data_table:
row = doc_table.add_row()
row_cells = row.cells
row_cells[0].text = str(row_num + 1) # 序號,需要轉換成字符串
row_cells[1].text = data['節點名稱']
row_cells[2].text = data['審批人員']
row_cells[3].text = data['審批方式']
row_cells[4].text = ''
# 水平居中
p = row_cells[0].paragraphs[0]
p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
row.height = Cm(0.6) # 行高
# 垂直居中
for j in range(0, 5):
row_cells[j].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
row_num = row_num + 1
doc.add_paragraph(text='', style=None) # 換行
doc.save(self.word_file)
以上就是python 將Excel轉Word的示例的詳細內容,更多關于python Excel轉Word的資料請關注腳本之家其它相關文章!
您可能感興趣的文章:- python提取word文件中的所有圖片
- python實現某考試系統生成word試卷
- 使用Python自動化Microsoft Excel和Word的操作方法
- Python 制作詞云的WordCloud參數用法說明
- Python WordCloud 修改色調的實現方式
- Python 自動化修改word的案例
- Python實現Word文檔轉換Markdown的示例
- python3處理word文檔實例分析
- Python word文本自動化操作實現方法解析
- Python快速優雅的批量修改Word文檔樣式