Python文本數據互相轉換(pandas and win32com)

(工做以後,就讓本身的身心都去休息吧)python

今天介紹一下文本數據的提取和轉換,這裏主要實例的轉換爲excel文件(.xlsx)轉換world文件(.doc/docx),同時須要使用win32api,同pywin32庫。windows

pandas庫我以前的博客裏面都有詳細的介紹和使用,這裏主要介紹下win32庫。api

PyWin32是一個Python庫,能夠爲Python提供Windows擴展。換句話說,它容許您訪問各類Windows功能 - 至少Microsoft Office的功能 - 而無需使用Microsoft的一種語言,如Visual Basic或C#。佈局

win32com模塊的下載:https://sourceforge.net/projects/pywin32/files/pywin32/(對應你的windows版本)字體

同時分享Galal Aly's博主:http://new.galalaly.me/2011/09/use-python-to-parse-microsoft-word-documents-using-pywin32-library/ui

Pywin32庫的一些概念:spa

  1.PyWin32是一個包裝器,它使您可使用Visual Basic for Applications(VBA)中提供的相同方法和屬性,但使用Python的語法。.net

  2.這是Word 2007開發人員參考,有用的部分是對象模型參考我必須檢查它們以瞭解可用的方法和屬性,所以它們很是重要。excel

  3.在任何參考資料中,您都會找到一些用VBA編寫的示例。您所要作的就是將它們轉換爲Python的語法。code

首先介紹下win32com:

1 # coding: UTF-8
2 import win32com.client
3 WordApp = win32com.client.Dispatch("Word.Application") 
4 WordApp.Visible = False

1.由於你使用的是中國漢字,windows中文本文檔大多數都是漢子處理,因此前提必定要加上# coding: UTF-8。

2.引入win32com模塊。

3.打開world應用程序,python操做world程序以便寫入文件。

4.是否在桌面打開world程序,這裏的False就是不須要打開,反之爲True。

這裏主要介紹win32api的一些屬性,主要爲操做world文檔所使用:

#新建空文檔
docx=WordApp.Documents.Add()
#打開指定文檔
docx = WordApp.Documents.Open(r'C:\Users\Administrator\Desktop\b.docx')
#保存到指定文檔
docx.SaveAs(r"c:\Users\Administrator\Desktop\c.doc")  # 文檔保存
#關閉文檔,需在保存文檔以後
docx.Close(-1) 

這裏須要特別注意的是,SaveAs爲另存文件,便可以不須要建立文件,另外一個是打開指定文檔,這裏若是你不須要存入一個文檔的話,就只須要打開一個文檔存到另外一個文檔也能夠,這裏能夠doc能夠轉換docx文件。

可是,若是你都要操做在你個world文件內,那麼就須要追加一個docx文件內:

1 #新建空文檔
2 docx=WordApp.Documents.Add()
3 #打開指定文檔,進行操做
4 docx = WordApp.Documents.Open(r'C:\Users\Administrator\Desktop\b.docx')
5 #保存
6 docx.Save

這裏只須要Save便可,原理就是打開一個指定的world文件,將數據存入進去後保存便可。

這裏關於world文件的保存和添加介紹完。

下面介紹些world文件的一些屬性:

一、頁面屬性:

1 docx.PageSetup.PaperSize = 7            # 紙張大小, A3=6, A4=7 
2 docx.PageSetup.PageWidth = 8.7*28.35    # 紙張寬大小後PaperSize 就不須要了
3 docx.PageSetup.PageHeight = 13*28.35   # 紙張高大小  
4 docx.PageSetup.Orientation = 1          # 頁面方向, 豎直=0, 水平=1 
5 docx.PageSetup.TopMargin = 2.45*28.35   # 頁邊距上=2.45cm,1cm=28.35pt 
6 docx.PageSetup.BottomMargin = 2.45*28.35 # 頁邊距下=2.45cm 
7 docx.PageSetup.LeftMargin =0.75*28.35    # 頁邊距左=0.75cm
8 docx.PageSetup.RightMargin = 0.5*28.35   # 頁邊距右=0.5cm  

二、頁面佈局:

 1 sel = WordApp.Selection       # 獲取Selection對象
 2 sel.InsertBreak(8)            # 插入分欄符=8, 分頁符=7 
 3 sel.Font.Name = "宋體"         # 字體
 4 sel.Font.Size = 11            # 字大
 5 sel.Font.Bold = True          # 粗體
 6 sel.Font.Italic = True        # 斜體
 7 sel.Font.Underline = True     # 下劃線 
 8 sel.ParagraphFormat.LineSpacing = 2*12   # 設置行距,1行=12磅
 9 sel.ParagraphFormat.Alignment = 1      # 段落對齊,0=左對齊,1=居中,2=右對齊
10 sel.TypeText("aaa")       # 插入文字
11 sel.TypeParagraph()       # 插入空行 
12 sel.TypeText("\n")        #插入空白行

三、表格:

 1 tab=docx.Tables.Add(sel.Range, 7, 2)  # 增長一個16行2列的表格 
 2 tab.Style = "網格型"              # 顯示錶格邊框
 3 tab.Columns(1).SetWidth(2.4*28.35, 0) #調整第一列寬
 4 tab.Columns(2).SetWidth(5.5*28.35, 0)
 5 tab.Rows.Alignment = 1                # 表格對齊,0=左對齊,1=居中,2=右對齊
 6 tab.CellCellCellCell(1,1).Range.Text = "aaa"    # 填充內容,注意Excel中使用wSheet.Cells(i,j)   
 7 sel.MoveDown(5, 16)              # 向下移動2行,5=以行爲單位 
 8 line_cells = tab.columns[0].cells    #第一列全部空格  0,1表明第幾列
 9 line_cells[0].Range.Text= 'N'      #第一列第一個空格中添加「N」
10 line_cells[1].Range.Text = ''.decode('utf-8') 
11 line_cells[2].Range.Text = ''.decode('utf-8') 
12 line_cells[3].Range.Text = '數量'.decode('utf-8') 
13 line_cells[4].Range.Text = '日期'.decode('utf-8') 
14 line_cells[5].Range.Text = '名稱'.decode('utf-8') 
15 line_cells[6].Range.Text = '編號'.decode('utf-8')

貼上Pandas模塊和win32com的完整代碼(主要看分佈):

 1 # coding: UTF-8
 2 import win32com.client
 3 import time
 4 import pandas as pd
 5 def parser():
 6     df = pd.read_excel('C:\\Users\\Administrator\\Desktop\\222.xlsx')
 7     pd.set_option('display.width',None)
 8     WordApp = win32com.client.Dispatch("Word.Application") 
 9     #WordApp.Visible = False
10 
11     
12     for i in xrange(0,len(df)):
13         Pn =  df.iloc[i,0].encode('utf-8')
14         partno = df.iloc[i,1].encode('utf-8')
15         manufacturer = df.iloc[i,2]
16         quantity = str(int(df.iloc[i,3]))
17         contractnum = df.iloc[i,4].encode('utf-8')
18         #print type(contractnum)
19         #print manufacturer
20         doc=WordApp.Documents.Add()
21         doc = WordApp.Documents.Open(r'C:\Users\Administrator\Desktop\b.docx')
22         doc.PageSetup.PageWidth = 9*28.35
23         doc.PageSetup.PageHeight = 13*28.35
24         doc.PageSetup.LeftMargin = 0.6*28.35
25         doc.PageSetup.RightMargin = 0.5*28.35
26 
27         sel = WordApp.Selection
28         sel.Font.Name = "宋體"
29         sel.Font.Size = 11
30         sel.TypeText("\n")
31         sel.TypeText("\n")
32         sel.TypeText("\n")
33         sel.TypeText("\n")
34         sel.TypeText("\n")
35         sel.TypeText("\n")
36         sel.TypeText("\n")
37         tab=doc.Tables.Add(sel.Range, 7, 2)
38         #print type(tab.location)
39         tab.Style = "網格型".decode('utf-8')
40         tab.Columns(1).SetWidth(2.4*28.35, 0)
41         tab.Columns(2).SetWidth(5.5*28.35, 0)
42         line_cells = tab.columns[0].cells
43         line_cells[0].Range.Text= 'N'
44         line_cells[1].Range.Text = ''.decode('utf-8') 
45         line_cells[2].Range.Text = ''.decode('utf-8') 
46         line_cells[3].Range.Text = '數量'.decode('utf-8') 
47         line_cells[4].Range.Text = '日期'.decode('utf-8') 
48         line_cells[5].Range.Text = '名稱'.decode('utf-8') 
49         line_cells[6].Range.Text = '編號'.decode('utf-8')
50         #print help(doc.SaveAs)
51         doc.Save
52         print 'Is oK!'
53         #doc.SaveAs(r'C:\Users\Administrator\Desktop\b.docx')
54     doc.Close()
55     WordApp.Quit()
56 if __name__ == '__main__':
57     parser()

這裏主要注意下下操做world程序和for循環的位置就能夠了,還有close,否則你的程序就會報錯,由於你打開一個world程序未關閉,再次打開windows會提示未保存文檔不可操做,因此程序會報錯!

更多技術信息添加羣:607021567

相關文章
相關標籤/搜索