Python辦公自動化之Excel轉Word

在平常工做中,Python在辦公自動化領域應用很是普遍,如批量將多個Excel中的數據進行計算並生成圖表,批量將多個Excel按固定格式轉換成Word,或者定時生成文件併發送郵件等場景。本文主要以一個簡單的小例子,簡述Python在Excel和Word方面進行相互轉換的相關知識點,謹供學習分享使用,若有不足之處,還請指正。python

相關知識點

本文主要是將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  以下所示:app

數據源文件

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

 核心代碼

本文核心源碼,主要分三部分:學習

導入相關模塊包,以下所示:字體

1 import xlrd
2 from docx import Document
3 from docx.enum.section import WD_ORIENTATION
4 from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
5 from docx.shared import Pt, Cm, RGBColor
6 from docx.oxml.ns import qn
7 from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
View Code

讀取Excel,以下所示:spa

 1     def read_excel(self):
 2         """讀取Excel"""
 3         book = xlrd.open_workbook(self.excel_file)
 4         sheet = book.sheet_by_name(self.sheet_name)
 5         nrows = sheet.nrows  # 行數
 6         ncols = sheet.ncols  # 列數
 7         datas = []  # 存放數據
 8         # 第一列 標題
 9         keys = sheet.row_values(0)
10         for row in range(1, nrows):
11             data = {}  # 每一行數據
12             for col in range(0, ncols):
13                 value = sheet.cell_value(row, col)  # 取出每個單元格的數據
14                 # 替換到特殊字符
15                 value = value.replace('<', '').replace('>', '').replace('$', '')
16                 data[keys[col]] = value
17                 # 截取第一列元素
18                 if col == 0:
19                     first = ''  # 截取元素 第1
20                     second = ''  # 截取元素 第2
21                     third = ''  # 截取元素 第3
22                     arrs = value.lstrip('/').split('/')  # 去掉第一個/ 而後再以/分組
23                     if len(arrs) > 0:
24                         if len(arrs) == 1:
25                             first = arrs[0]
26                             second = first
27                             third = second
28                         elif len(arrs) == 2:
29                             first = arrs[0]
30                             second = arrs[1]
31                             third = second
32                         elif len(arrs) == 3:
33                             first = arrs[0]
34                             second = arrs[1]
35                             third = arrs[2]
36                         else:
37                             first = arrs[0]
38                             second = arrs[1]
39                             third = arrs[2]
40                     else:
41                         first = value.ltrip('/')
42                         second = first
43                         third = second
44                     data['first'] = first
45                     data['second'] = second
46                     data['third'] = third
47                 # 截取第一列結束
48             datas.append(data)
49         return datas
View Code

生成Word部分:插件

  1     def write_word(self, datas):
  2         """生成word文件"""
  3         if len(datas) < 1:
  4             print('Excel沒有內容')
  5             return
  6         # 定義word文檔對象
  7         doc = Document()
  8         # 添加橫向
  9         section = doc.sections[0]  # doc.add_section(start_type=WD_SECTION_START.CONTINUOUS)  # 添加橫向頁的連續節
 10         section.orientation = WD_ORIENTATION.LANDSCAPE
 11         page_h, page_w = section.page_width, section.page_height
 12         section.page_width = page_w  # 設置橫向紙的寬度
 13         section.page_height = page_h  # 設置橫向紙的高度
 14         # 設置字體
 15         doc.styles['Normal'].font.name = u'宋體'
 16         doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋體')
 17         # 獲取第3部分(部門) 並去重
 18         data_third = []
 19         for data in datas:
 20             third = data['third']
 21             if data_third.count(third) == 0:
 22                 data_third.append(third)
 23         for third in data_third:
 24             h2 = doc.add_heading(third, level=2)  # 寫入部門,二級標題
 25             run = h2.runs[0]  # 能夠經過add_run來設置文字,也能夠經過數組來獲取
 26             run.font.color.rgb = RGBColor(0, 0, 0)
 27             run.font.name = u'宋體'
 28             doc.add_paragraph(text='', style=None)  # 增長空白行 換行
 29             # 開始獲取模板
 30             data_template = []
 31             for data in datas:
 32                 if data['third'] == third:
 33                     template = {'first': data['first'], '模板名稱': data['模板名稱']}
 34                     if data_template.count(template) == 0:
 35                         data_template.append(template)
 36             # 獲取模板完成
 37             # 遍歷模板
 38             for template in data_template:
 39                 h3 = doc.add_heading(template['模板名稱'], level=3)  # 插入模板名稱,三級標題
 40                 run = h3.runs[0]  # 能夠經過add_run來設置文字,也能夠經過數組來獲取
 41                 run.font.color.rgb = RGBColor(0, 0, 0)
 42                 run.font.name = u'宋體'
 43                 doc.add_paragraph(text='', style=None)  # 換行
 44                 data_table = filter(
 45                     lambda data: data['third'] == third and data['模板名稱'] == template['模板名稱'] and data['first'] ==
 46                                  template['first'], datas)
 47                 data_table = list(data_table)
 48                 # 新增表格 4行5列
 49                 doc_table = doc.add_table(rows=4, cols=5)
 50                 doc_table.style = "Table Grid"
 51                 doc_table.style.font.size = Pt(9)
 52                 doc_table.style.font.name = '宋體'
 53 
 54                 # 合併單元格 賦值
 55                 doc_table.rows[0].cells[1].merge(doc_table.rows[0].cells[4])
 56                 doc_table.rows[1].cells[1].merge(doc_table.rows[1].cells[4])
 57                 doc_table.rows[2].cells[1].merge(doc_table.rows[2].cells[4])
 58                 doc_table.rows[0].cells[0].text = '流程名稱:'
 59                 doc_table.rows[0].cells[1].text = data_table[0]['模板名稱']
 60                 doc_table.rows[1].cells[0].text = '使用人:'
 61                 doc_table.rows[1].cells[1].text = data_table[0]['first']
 62                 doc_table.rows[2].cells[0].text = '流程說明:'
 63                 doc_table.rows[2].cells[1].text = data_table[0]['流程說明']
 64 
 65                 # 設置標題
 66                 head_cells = doc_table.rows[3].cells  # 前面還有三行,特殊處理
 67                 head_cells[0].text = '節點'
 68                 head_cells[1].text = '節點名'
 69                 head_cells[2].text = '處理人員'
 70                 head_cells[3].text = '處理方式'
 71                 head_cells[4].text = '跳轉信息'
 72                 # 設置列寬
 73                 head_cells[0].width = Cm(1.9)
 74                 head_cells[1].width = Cm(4.83)
 75                 head_cells[2].width = Cm(8.25)
 76                 head_cells[3].width = Cm(2.54)
 77                 head_cells[4].width = Cm(5.64)
 78                 # 第1 列水平居中,並設置行高,全部單元格內容垂直居中
 79                 for i in range(0, 4):
 80                     # 水平居中
 81                     p = doc_table.rows[i].cells[0].paragraphs[0]
 82                     p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
 83                     doc_table.rows[i].height = Cm(0.6)  # 行高
 84                     # 垂直居中
 85                     for j in range(0, 5):
 86                         doc_table.rows[i].cells[j].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
 87 
 88                 # 生成表格並填充內容
 89                 row_num = 0
 90                 for data in data_table:
 91                     row = doc_table.add_row()
 92                     row_cells = row.cells
 93                     row_cells[0].text = str(row_num + 1) # 序號,須要轉換成字符串
 94                     row_cells[1].text = data['節點名稱']
 95                     row_cells[2].text = data['審批人員']
 96                     row_cells[3].text = data['審批方式']
 97                     row_cells[4].text = ''
 98                     # 水平居中
 99                     p = row_cells[0].paragraphs[0]
100                     p.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
101                     row.height = Cm(0.6)  # 行高
102                     # 垂直居中
103                     for j in range(0, 5):
104                         row_cells[j].vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
105                     row_num = row_num + 1
106 
107                 doc.add_paragraph(text='', style=None)  # 換行
108         doc.save(self.word_file)
View Code

備註

子曰:「不患無位,患因此立。不患莫己知,求爲可知也。excel

相關文章
相關標籤/搜索