Python_13-Office文件数据操作

目录:

1.1      安装win32com模块

1.2      Access数据库操作

1.2.1       建立db1.db数据库,设计一张表t_student_b

1.3      Excel文件操作

1.3.1       读取Excel

1.4      Word文件操作

1.4.1       示例1:打开,另存为

1.4.2       示例2:更多功能

 

 

 

1.1   安装win32com模块

 

下载地址:

http://sourceforge.net/projects/pywin32/

 

1.2   Access数据库操作

1.2.1   建立db1.db数据库,设计一张表t_student_b

 

示例

#Python操作Access数据库步骤之1、建立数据库连接

import win32com.client  

conn = win32com.client.Dispatch(r'ADODB.Connection')

print '111'

DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=d:\\python279\\db1.mdb;'  

conn.Open(DSN)

print '222'

#Python操作Access数据库步骤之2、打开一个记录集

rs = win32com.client.Dispatch(r'ADODB.Recordset')  

rs_name = 't_student_b'#表名  

rs.Open('[' + rs_name + ']', conn, 1, 3)

 

#Python操作Access数据库步骤之3、对记录集操作

rs.AddNew()  

rs.Fields.Item(1).Value = '102'

rs.Fields.Item(2).Value = 'Li Yong'

rs.Update()

 

sql_statement = "insert into t_student_b (studno, studname) values ('201101', 'LiLee')"

#sql_statement = 'select * from t_student_b order by studno';

print '333'

conn.Execute(sql_statement)  

print '444'

 

conn.Close() 

 

 

1.3   Excel文件操作

1.3.1   读取Excel

 

编写操作类

from win32com.client import constants, Dispatch

 

class EasyExcel:

 

    def __init__(self, filename=None):

        self.xlApp = Dispatch('Excel.Application')

        if filename:

            self.filename = filename

            self.xlBook = self.xlApp.Workbooks.Open(filename)

        else:

           print "please input the filename"

 

    def close(self):

        self.xlBook.Close(SaveChanges=0)

        del self.xlApp

 

    def getCell(self, sheet, row, col):

        "Get value of one cell"

        sht = self.xlBook.Worksheets(sheet)

        return sht.Cells(row, col).Value

  

    def getRange(self, sheet, row1, col1, row2, col2):

        "return a 2d array (i.e. tuple of tuples)"

        sht = self.xlApp.Worksheets(sheet)

        return sht.Range(sht.Cells(row1, col1), sht.Cells(row2, col2)).Value

 

示例:

#from easyExcel import EasyExcel

#from texcel import EasyExcel

 

excelProxy = EasyExcel("d:\\python279\\test.xls")

 

content=excelProxy.getRange("sheet1",1,1,2,2)

   

print content

 

1.4   Word文件操作

 

 

要使用Python控制MS Word,您需要先安装win32com套件,这个套件可以到 http://sourceforge.net/projects/pywin32/ 找到。您需要先import win32com模块才能进行Word的控制。

 

1.4.1   示例1:打开,另存为

from win32com.client import Dispatch, constants

from win32com.client.gencache import EnsureDispatch

 

EnsureDispatch('Word.Application') #makepy 导入Word类库,否则constants无法使用

 

msword = Dispatch('Word.Application')

msword.Visible = True #是否可见

msword.DisplayAlerts = 0

strDir='d:\\python279\\';

doc = msword.Documents.Open(FileName = strDir + r'test.doc') #打开已有文件

newdoc = msword.Documents.Add() #添加新文件

 

newdoc.SaveAs('new.doc') #另存为

 

1.4.2   示例2:更多功能

#Python 操作Word(Excel、PPT等通用)

 

import win32com

from win32com.client import Dispatch, constants

 

w = win32com.client.Dispatch('Word.Application')

# 或者使用下面的方法,使用启动独立的进程:

# w = win32com.client.DispatchEx('Word.Application')

 

# 后台运行,不显示,不警告

w.Visible = 1

w.DisplayAlerts = 0

filenamein = 'test.doc'

# 打开新的文件

#doc = w.Documents.Open( FileName = filenamein )

worddoc = w.Documents.Add() # 创建新的文档

 

# 插入文字

#myRange = doc.Range(0,0)

myRange = worddoc.Range(0,0)

myRange.InsertAfter('Hello from Python! 111\n')

w.Selection.TypeParagraph;   #换行

myRange.InsertAfter('Hello from Python! 222\n')

#wordSel = myRange.Select()

myRange = worddoc.Range(0,0)

w.Selection.Style = constants.wdStyleHeading1 #找不到Style

 

# 正文文字替换

OldStr = 'Hello'

NewStr = 'How are you'

 

#w.Selection.Find.ClearFormatting()

#w.Selection.Find.Replacement.ClearFormatting()

#w.Selection.Find.Execute(OldStr, False, False, False, False, False, True, 1, True, NewStr, 2)

 

# 页眉文字替换

print('page header:')

#w.ActiveDocument.Sections[0].Headers[0].Range.Find.ClearFormatting()

#w.ActiveDocument.Sections[0].Headers[0].Range.Find.Replacement.ClearFormatting()

#w.ActiveDocument.Sections[0].Headers[0].Range.Find.Execute(OldStr, False, False, False, False, False, True, 1, False, NewStr, 2)

 

 

# 表格操作

print('table:')

#myRange = worddoc.Range(0,0)

#worddoc.Tables.Add(myRange, 5, 4)

 

w.Selection.TypeParagraph;   #换行

 

#w.Selection.TypeText = 'test';

#w.Content.InsertAfter.Text = 'test'

#w.Selection.TypeParagraph;

 

myRange = worddoc.Range(worddoc.Sentences.Last.End -1,worddoc.Sentences.Last.End -1)

#w.Selection.Style = '正文'

w.Selection.ClearFormatting()

myRange.InsertAfter('Hello from Python! 333\n')

myRange.InsertAfter('Hello from Python! 444\n')

myRange.InsertAfter('Hello from Python! 555\n')

 

myRange.InsertAfter('Hello from Python! 333\n')

myRange = worddoc.Range(worddoc.Sentences.Last.End -1,worddoc.Sentences.Last.End -1)

w.ActiveDocument.Tables.Add(myRange, 2, 5)

#w.ActiveDocument.Tables.Add(wmyRange, 2, 5)

'''

if w.Selection.Tables(1).Style <> "网格型":

    w.Selection.Tables(1).Style = "网格型"

    w.Selection.Tables(1).ApplyStyleHeadingRows = True

    w.Selection.Tables(1).ApplyStyleLastRow = True

    w.Selection.Tables(1).ApplyStyleFirstColumn = True

    w.Selection.Tables(1).ApplyStyleLastColumn = True

'''

   

#w.Selection.

#worddoc.Tables[0].Rows[0].Cells[0].Range.Text ='123123'

#worddoc.Tables[0].Rows.Add() # 增加一行

 

# 转换为html

print('html:')

filenameout = 'd:\\python279\\mytest.html';

wc = win32com.client.constants

w.ActiveDocument.WebOptions.RelyOnCSS = 1

w.ActiveDocument.WebOptions.OptimizeForBrowser = 1

w.ActiveDocument.WebOptions.BrowserLevel = 0 # constants.wdBrowserLevelV4

w.ActiveDocument.WebOptions.OrganizeInFolder = 0

w.ActiveDocument.WebOptions.UseLongFileNames = 1

w.ActiveDocument.WebOptions.RelyOnVML = 0

w.ActiveDocument.WebOptions.AllowPNG = 1

#w.ActiveDocument.SaveAs( FileName = filenameout, FileFormat = wc.wdFormatHTML ) # right work

 

# 打印

#doc.PrintOut()

#worddoc.PrintOut()

# 关闭

#doc.Close()

#worddoc.Close()

#w.Documents.Close(wc.wdDoNotSaveChanges)

#w.Quit()

 

其他例子:

http://www.th7.cn/Program/Python/201409/277859.shtml

posted @ 2015-12-31 14:51  jiu~  阅读(1155)  评论(0编辑  收藏  举报