1. 程式人生 > >用Python讀取Word文件並寫入Excel(二)

用Python讀取Word文件並寫入Excel(二)

對於從word文件中得到的資訊,我們往往需要寫入excel,以便我們做後續的資料處理。在此,我們同樣利用win32 的api,寫入excel的方法如下:

def write_excel(workbook,i_in,name_in,Gender_in,School_in,Major_in,Grade_in,Birth_in,Telephone_in,QQ_in,
                QQEmail_in,Place_in,Address_in,Data_number,Weeks_in,participate_in,other_team_in,Witch_team_in):

    first_sheet=workbook.Worksheets(1
)//需要獲取excel first_sheet.Cells(i_in,3).value=name_in first_sheet.Cells(i_in,4).value=Gender_in first_sheet.Cells(i_in,5).value=School_in first_sheet.Cells(i_in,6).value=Major_in first_sheet.Cells(i_in,7).value=Grade_in first_sheet.Cells(i_in,8).value=Birth_in first_sheet.Cells(i_in
,9).value=Telephone_in first_sheet.Cells(i_in,10).value=QQ_in first_sheet.Cells(i_in, 11).value = QQEmail_in first_sheet.Cells(i_in,12).value =Place_in first_sheet.Cells(i_in,13).value=Address_in first_sheet.Cells(i_in, 14).value = Weeks_in first_sheet.Cells(i_in, 15).value = participate_in
first_sheet.Cells(i_in, 16).value = other_team_in first_sheet.Cells(i_in, 2).value = Data_number first_sheet.Cells(i_in, 1).value = Witch_team_in print('成功寫入:'+name_in+" 的資訊","這是第",i_in-rember_ever+1,"個") workbook.Save()

方法裡的每條語句都寫的很清楚,基本思路就是先建立並獲取excel,然後在Cells裡即表示儲存的位置。

將上一部分的提取和本部分的寫入相結合,完整程式碼如下:

#coding:utf-8
import win32com.client
import os
import win32com

from win32com.client import Dispatch, constants
from docx import Document
import time

def parse_docx(f,i,f_excel,Data_number):
  """讀取docx,返回姓名和行業
  """
  d = Document(f)
  t = d.tables[0]
  t_next=d.tables[1]
  #title= t.cell(0,1).text
  name = t.cell(1,1).text     #1
  Gender = t.cell(1,3).text   #1
  Race = t.cell(1,5).text     #1
  School=t.cell(2,1).text     #1
  Edu_back=t.cell(2,4).text   #1
  Major=t.cell(3,1).text      #1
  Grade=t.cell(3,4).text      #1
  Poli_Status=t.cell(4,1).text#1
  Place=t.cell(4,3).text      #1
  ID_card=t.cell(5,1).text    #1
  Date_birth=t.cell(5,4).text #1
  Telephone=t.cell(6,1).text  #1
  E_mail=t.cell(6,4).text     #1
  QQ=t.cell(7,1).text         #1
  Address=t.cell(7,4).text    #1
  Which_team=t.cell(8,1).text #1
  Weeks=t.cell(9,4).text
  participate=t.cell(10,4).text
  other_team=t.cell(11,4).text

#  Other=t_next.cell(1,1).text
  print(name, Gender,Race,School,Edu_back,Major,Grade,Poli_Status,Place,ID_card,Date_birth,Telephone,E_mail,QQ,Place,Address,Which_team,
        Weeks,participate,other_team,end='\n ')
  write_excel(f_excel,i,name,Gender,School,Major,Grade,Date_birth,Telephone, E_mail,QQ,Place,Address,Data_number,
              Weeks,participate,other_team,Which_team)
  rename("C:\My_Work",f,name,Data_number)

def write_excel(workbook,i_in,name_in,Gender_in,School_in,Major_in,Grade_in,Birth_in,Telephone_in,QQ_in,
                QQEmail_in,Place_in,Address_in,Data_number,Weeks_in,participate_in,other_team_in,Witch_team_in):

    first_sheet=workbook.Worksheets(1)
    first_sheet.Cells(i_in,3).value=name_in
    first_sheet.Cells(i_in,4).value=Gender_in
    first_sheet.Cells(i_in,5).value=School_in
    first_sheet.Cells(i_in,6).value=Major_in
    first_sheet.Cells(i_in,7).value=Grade_in
    first_sheet.Cells(i_in,8).value=Birth_in
    first_sheet.Cells(i_in,9).value=Telephone_in
    first_sheet.Cells(i_in,10).value=QQ_in
    first_sheet.Cells(i_in, 11).value = QQEmail_in
    first_sheet.Cells(i_in,12).value =Place_in
    first_sheet.Cells(i_in,13).value=Address_in

    first_sheet.Cells(i_in, 14).value = Weeks_in
    first_sheet.Cells(i_in, 15).value = participate_in
    first_sheet.Cells(i_in, 16).value = other_team_in
    first_sheet.Cells(i_in, 2).value = Data_number
    first_sheet.Cells(i_in, 1).value = Witch_team_in

    print('成功寫入:'+name_in+" 的資訊","這是第",i_in-rember_ever+1,"個")
    workbook.Save()

def rename(path,old_file,newname,Data_number):
    '''path="這裡替換為你的資料夾的路徑";
    filelist=os.listdir(path)#該資料夾下所有的檔案(包括資料夾)
    for files in filelist:#遍歷所有檔案
    Olddir=os.path.join(path,files);#原來的檔案路徑
    if os.path.isdir(Olddir):#如果是資料夾則跳過
    continue;'''
    Olddir=os.path.join(path,old_file);#原來的檔案路徑
    filename=os.path.splitext(old_file)[0];#檔名
    filetype=os.path.splitext(old_file)[1];#副檔名
 #   data_identi=
    Newdir=os.path.join(path,str(Data_number)+newname+filetype);#新的檔案路徑
    os.rename(Olddir,Newdir);#重新命名

def introduction():
    print("美仔你好,感謝使用本軟體,它將會快速的幫你完成工作")
    print("開始前,請將今天你收集的所有報名表放到C:\My_Work資料夾下,如果已經成功放置,請回復1,之後按回車")
    rece_ancer=input()
    while  (rece_ancer!='1'):
             rece_ancer=input("還沒準備好嘛,確認好了以後輸入1\n")
    print("好的,五秒鐘後開始工作,在這期間,請不要開啟word文件和excel文件哦\n")
    time.sleep(1)
    print("5")
    time.sleep(1)
    print("4")
    time.sleep(1)
    print("3")
    time.sleep(1)
    print("2")
    time.sleep(1)
    print("1")


if __name__ == "__main__":

  data_identifier = int(input("請輸入今天是幾月幾號,格式如:409、413、421,按回車結束\n"))
  while True:
        if(data_identifier>=101 and data_identifier<=1230):
             break
        else:
            print("請重新輸入")
            data_identifier=int(input())
  data_identifier = data_identifier * 100+1
  print("好的,接下來請按提示操作",data_identifier)
  introduction()

  w = win32com.client.Dispatch('Word.Application')
  excel = win32com.client.Dispatch('Excel.Application')
  workbook=excel.Workbooks.open('C:\My_Work\\海口分隊報名資訊錄入表(總表)+日期.xlsx')
  excel.Visible=False

  i=3
  # 遍歷檔案
  PATH = "C:\My_Work" # windows檔案路徑
  doc_files = os.listdir(PATH)

  rember_sheet=workbook.Worksheets(1)
  for rember_ever in range(3,1000):
          Value=rember_sheet.Cells(rember_ever,2).value
          print(Value,rember_ever)
          if(Value==None):
             break
  i=rember_ever
  print("從上次的第",i,"行錄入\n")

  for doc in doc_files:
    if os.path.splitext(doc)[1] == '.docx':
      try:
        parse_docx(PATH+'\\'+doc,i,workbook,data_identifier)
        i=i+1
        data_identifier=data_identifier+1
      except Exception as e:
        print(e) 
    elif os.path.splitext(doc)[1] == '.doc':
      try:
        parse_doc(PATH+'\\'+doc)
      except Exception as e:
        print (e)
  print("全部操作完成,好了,現在你可以到C:\My_Work資料夾下檢視資料,","今天一共寫了",i-rember_ever,"個人的資訊\n")
  print("辛苦啦,現在請把C:\My_Work下的報名表複製到對應日期的資料夾內,並從“海口分隊報名資訊錄入表(總表)+日期”這個檔案裡的資訊\n複製到總的資訊表上,壓縮傳到群裡\n")
  excel.Application.Quit()
  time.sleep(150)

相關推薦

Python讀取Word寫入Excel

對於從word文件中得到的資訊,我們往往需要寫入excel,以便我們做後續的資料處理。在此,我們同樣利用win32 的api,寫入excel的方法如下: def write_excel(workbook,i_in,name_in,Gender_in,Sch

Python讀取Word寫入Excel

工作中經常要處理大量的word文件,大部分內容都很簡單,比如說做一個彙總表,從發來的word文件裡提取名字、聯絡方式、地址等資訊,提取完之後還需要用Excel做彙總,對於十幾份的文件尚好,但對於成百份,

[日常]Python讀取word中的表格比較 2018-10-04

最近想對某些word文件(docx)的表格內容作比較, 於是找了一下相關工具. 參考Automate the Boring Stuff with Python中的word部分, 試用了python-docx - python-docx 0.8.7 documentation 演示如下.

python讀取配置模塊configparser參數詳解

string cts open mod fix error: 註釋 大於 default configparser.ConfigParser參數詳解 從configparser的__ini__中可以看到有如下參數: def __init__(self, defaul

python讀取word表格裡的資料

首先需要安裝相應的支援庫: 直接在命令列執行pip install python-docx 示例程式碼如下: import docx from docx import Document #

python讀取配置config.ini

one cli some out site 文件中 baseurl roo eas 還在學習中。。。寫的有點淩亂 感覺還是應該先學會讀取配置文件才行,把一些經常需要修改的但是又經常需要用到的參數放到配置文件中方便使用(我是這麽覺得的) 首先是config.ini的存放位

在Qt中調python,讀取csv,實現K近鄰算法(一)

修改 ref log nali show ofo ica blog 讀取csv文件 目錄: 1.從Qt中調用py腳本裏的一個無參函數,功能:打印"hello python"   a)相關配置   b)踩過的一些坑 2.從Qt中調用py腳本裏的一個有參函數並接收返回值

python 解析execl寫入

first info main urn odi 創建 exceptio append cell #!/usr/bin/env python#coding:utf-8import osimport xlrd,xlwtimport requests NatExeclFile=o

python讀取json轉成excel

dex with index odi 讀取 while cell with open __main__ python處理excel有xlwt,openpyxl等,而xlwt只支持excel2003,也就是最多有256列,而openpyxl則支持excel2007以上,最多6

nodejs將word轉為html檔案指令碼--獲取word內容

本來是想寫 用nodejs 或者 js 將word文件轉為html的指令碼, js在IE瀏覽器下有 new ActiveApplication 物件可以 獲取文件 nodejs 獲取文件看這篇http://www.jianshu.com/p/68a420a6

Android實戰——第三方服務之Bmob後端雲的增刪改查、上傳、獲取、修改密碼

tid blank 生成 src 上傳圖片 放置 第三方 b數 net 第三方服務之Bmob後端雲的增刪改查、上傳文件、獲取文件、修改密碼(二) 事先說明:這裏的一切操作都是在集成了BmobSDK之後實現的,如果對Bmob還不了解的話,請關註我第一篇Bmob文章 步

使用Swagger2Markup實現API的靜態部署:Markdown和Confluence

在上一篇《使用Swagger2Markup實現API文件的靜態部署(一):AsciiDoc》中,我們介紹瞭如何使用 Swagger2Markup將Swagger文件轉換成AsciiDoc,再將AsciiDoc轉換成靜態HTML。下面,本文將繼續介紹Swagger2Ma

讀取word提取和寫入數據基於python 3.6

number import utf-8 for 文本 pre ext 3.6 war #!/usr/bin/python3# -*- coding: utf-8 -*-# @File : delete_file# @Author : moucong# @Date

python 讀取越來越慢判斷 key 在 map 中,千萬別 in keys()

方案 使用 tail 千萬 上傳 true 文件夾 blog alt 背景: 今天樂樂姐寫代碼,讀取一個四五百兆的文件,然後做一串的處理。結果處理了一天還沒有出來結果。問題出在哪裏呢? 解決: 1. 樂樂姐打印了在不同時間點的時間,直接print time() 即可。發

python 迴圈讀取txt 轉換成csv

# -*- coding: utf-8 -*- """ Created on Fri Jul 29 15:49:06 2016 @author: user """ import os #從檔

Python中辦公軟讀取word和讀出保存別

辦公 port def eas -s size pycha hsi 兩種 #讀word文件import win32comimport win32com.clientdef readWordFile(path): #調用系統word功能,可以出來doc和docx兩種文件

python】在dom讀取xml檔對象、元素對象的類型的type()時 出現<type 'instance'> 而不是具體類型時?

一個 tps env ldo article err sin https type 參考 【獲取python對象的類型名字 不希望全都只顯示<type ‘instance‘>?】 【type() 和 isinstance() 的區別】 【python中

Makefile中怎樣調python和perl為自己提供須要的數據

print erl col shel ria 實例代碼 space shell eight Makefile中怎樣調用python和perl文件為自己提供須要的數據,利用print函數對外輸出數據 實例代碼例如以下 perl.pl #!/usr/bin/per

python 讀取 配置

python 讀取 配置文件 讀取方法: def get(section,option): cp = ConfigParser.SafeConfigParser() cp.read(os.path.split(os.path.realpath(__file__))[] + )

python 讀取

treat pan 出現 擔心 code including open hand you 要讀取個大文件,文件大概是3G左右,擔心read會出現內存溢出的情況,網上找了個靠譜的用法: with open(...) as f: for line in f: