• 使用python读取word,写入execl


    word里面有2张表,需要找到第二张表,并写入execl中:

    代码如下:

    #coding:utf-8
    import os
    from docx import Document
    import win32com
    from win32com.client import Dispatch, constants
    
    def parse_docx(f,title):
        d = Document(f)
        for t in d.tables:
            '''获取需要的表'''
            tbTitle = t.cell(0, 0).text
            if title == tbTitle:
                tableInfo = []
                columnLen = len(t.columns)
                rowLen = len(t.rows)
                for i in range(0,columnLen):
                    tmp = []
                    for row in t.rows:
                        tmp.append(row.cells[i].text)
                    #删除第一个元素->表名
                    del(tmp[0])
                    tableInfo.append(tmp)
                #返回的后两个参数表示tableInfo表的行数和列数
                return [tbTitle,tableInfo,rowLen-1,columnLen]
        return None
    
    def writeExecl(fileName,sheet,tableInfo):
        excel = win32com.client.Dispatch('Excel.Application')
        excel.Visible=0
        excel.DisplayAlerts=0
        #对传入文件名的处理
        if fileName:
            if os.path.exists(fileName):
                workbook = excel.Workbooks.Open(fileName)
            else:
                workbook = excel.Workbooks.Add()
                workbook.SaveAs(fileName)
        else:
            workbook = excel.Workbooks.Add()
    
        try:
            sht = workbook.Worksheets(sheet)
        except:
            sheetNew = workbook.Worksheets.Add()
            sheetNew.Name =sheet
            sheetNew.Activate()
            sht = workbook.Worksheets(sheet)
        #execl表格是从1开始的
        sht.Cells(1, 1).Value = tableInfo[0]
        #把tableInfo看作是一行数据,依次赋值
        for i in range(0,tableInfo[3]):
            for j in range(0,tableInfo[2]):
                sht.Cells(j+2, i+1).Value = tableInfo[1][i][j]
    
        workbook.Save()
        excel.Application.Quit()
    
    if __name__ == "__main__":
        docxFile = "123.docx"
        execlFile = "roro.xlsx"
        sheet = "roro"
    
        tableName = "内科"
        #读取word中tableName的内容
        tableInfo = parse_docx(docxFile,tableName)
    
        #处理execl
        writeExecl(execlFile,sheet,tableInfo)

     运行后生成文件 roro.xlsx,内容如下:

  • 相关阅读:
    J2SE-反射
    c3p0 连接数据库失败的问题
    c# 调用存储过程
    存储过程使用truncate时
    Parcelable intent传递对象时,需要将该对象实现Parcelable 或者Serializable
    android intent 在打开设置activity的时候在监听事件的内部 适用setclass()方法时 不是直接适用this 关键字
    c# 读取appconfig文件
    Oracle 连接数据库的几种方式
    通过反射获得方法,和绑定事件
    js 验证
  • 原文地址:https://www.cnblogs.com/charlieroro/p/8490560.html
Copyright © 2020-2023  润新知