zoukankan      html  css  js  c++  java
  • pdf对excel数据转换代码备份

    pdf对excel数据转换代码备份
     一.综合测试代码

    # -*- coding: utf-8 -*-
    """
    Created on Wed Dec  2 15:46:02 2015
     
    @author: Administrator
    13-1-001之后的就发生读取发生错误,index=1976
    index=4100发生错误
    """
    import PyPDF2,os,openpyxl
    from openpyxl.cell import get_column_letter,column_index_from_string
     
    #打开Excel
    #测试Excel
    '''
    wb_test=openpyxl.load_workbook('example.xlsx')
    sheet_test=wb_test.active
    for cellObj in sheet_test.columns[3]:
        print(cellObj.value)
        '''
     
    #打开处理的Excel
    wb=openpyxl.load_workbook('lijia2.xlsx')  
    sheet=wb.active
    column=sheet.columns[2]
    column_C_num=len(column)  #4483个处理pdf
    column_C_num-=1            #去掉标题,要减一
     
    column_index=column_index_from_string('J') #J的索引号最终是10
    column_K=sheet.columns[column_index]   #要填写的K列
     
     
    column_J=sheet.columns[column_index-1]
    filenames_column_J=[]         #最终要填写的文件名集合
    for cellObj in column_J[1:]:   #console显示不全前面内容,出现第一项不是第一个
        #print(cellObj.value)
        filenames_column_J.append(cellObj.value)
        
    #Excel的J栏要处理pdf数量
    column_J_num=len(filenames_column_J)   #4483个处理pdf文档
     
    if column_C_num!=column_J_num:
        raise NameError
     
     
     
    #1.搜集所有pdf文档
    pdfFiles=[]
    for filename in os.listdir('.'):#返回当前文件夹的所有文件:
        if filename.endswith('.pdf'):
            pdfFiles.append(filename)
            
    pdfFile_num=len(pdfFiles)     #文件夹pdf数量
     
     
    #删除不需要的pdf文件
    for filename in pdfFiles:
        if filename not in filenames_column_J:
            os.remove(filename)
     
    #filename_error:Excel有的pdf文件,而路径找不到的pdf列表
    filename_error=[]  
    for i in filenames_column_J:
        if i not in pdfFiles:
            filename_error.append(i)
            
    #异常排除
    if filename_error!=[] or pdfFile_num!=column_J_num:
        raise NameError
     
    '''
    #当文件名由字母和数字组成时,文件路径排序会和Excel排序不一样
    for i in range(column_J_num):
        if pdfFiles[i]!=filenames_column_J[i]:  #审核文件名是否一致
            print ('wrongIndex:',i)
            raise NameError
    '''
     
     
     
    #需要对Excel的K行建立一个字典,方便找到索引
     
     
     
    #依次打开Excel对应的pdf文件名,写入cell
    loop=column_J_num  #循环次数要和文件名一致,1976及其之后的pdf,Python不能识别,只能处理到这一步
     
    for i in range(loop):
        #print ('file:',i)
        
        #每100行显示print
        if i%100==0:
            print 'fileindex:',i
            
            
        filename=filenames_column_J[i]
        try:
            
            pdfFileObj=open(filename,'rb')
            pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
            pages=pdfReader.numPages #显示页数 在第4100行时读取pdfReader也会出错
        except:
            continue
       
        #pageObj=pdfReader.getPage(0) #读取第一页的字符,第一页可读取
        #content=pageObj.extractText() #输出第一页字符
        
        #页面写入
        content=""
        for page in range(pages):
            try:
                pageObj=pdfReader.getPage(page) #读取第一页的字符,第一页可读取
                content+=pageObj.extractText() #输出第一页字符
            except:
                continue
                
        column_K[i+1].value=content        #不用转换,可直接写入excel,第二页pdf也可写入excel
        pdfFileObj.close()
     
    #行高和行宽设定
    sheet.height=12
    sheet.column_dimensions['K'].width=20
     
    #审核单元格里是否有空白,有多少空白
    list_blank_cell=[]
    for cell in column_K:
        #print"cell.value:",cell.value
        if cell.value==None:
            list_blank_cell.append(cell)
     
    print "list_blank_cell:",list_blank_cell
    print "number of blank cell:",len(list_blank_cell)
    #检测出28-3-0005.pdf对应的单元格是空白,经核实,无法打开此文档
    wb.save('lijia2.xlsx') 
     



    二.单个样本测试
    # -*- coding: utf-8 -*-
    """
    Created on Fri Dec  4 14:05:39 2015
    单文件数据转移测试
    @author: Administrator
    """
     
    import PyPDF2,os,openpyxl
    from openpyxl.cell import get_column_letter,column_index_from_string
     
    #打开处理的Excel
    wb=openpyxl.load_workbook('example.xlsx')
    sheet=wb.active
     
    cell=sheet['K3']
     
    filename="13-1-001.pdf"
    pdfFileObj=open(filename,'rb')
     
    try:
        pdfFileObj=open(filename,'rb')
        pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
        content=pageObj.extractText()
        pageObj=pdfReader.getPage(0)
    except:         #不知道什么原因出错,except后面就不要加名字
        print("wrong")
        
    print("done")
        
        
        
     
     
     
    '''
       
     
     
    content=pageObj.extractText()    #错误所在,文字无法提取,尝试换Python2版本,
                                     #或把pdf降解到Word文档,再转换到Excel里
     
    #print('content:',content)
     
    cell.value=content
     
    print("well done")
     
    wb.save('example.xlsx')
    content=""
    for page in range(pages):
        print ('page:',page)
        pageObj=pdfReader.getPage(page) #读取第一页的字符,第一页可读取
        print("ok")
        content+=pageObj.extractText() #输出第一页字符
        print('ok1')
    column_K[i+1].value=content        #不用转换,可直接写入excel,第二页pdf也可写入excel
    pdfFileObj.close()
     
    wb.save('example.xlsx') 
    '''


     
    三,小样本测试


    # -*- coding: utf-8 -*-
    """
    Created on Wed Dec  2 15:46:02 2015
     
    @author: Administrator
    13-1-001之后的就发生读取发生错误,index=1976
    小样本测试完毕,不能打开和提取文字的语句发生异常时,程序自动跳到下一行
    """
    import PyPDF2,os,openpyxl
    from openpyxl.cell import get_column_letter,column_index_from_string
     
    #打开Excel
    #测试Excel
    '''
    wb_test=openpyxl.load_workbook('example.xlsx')
    sheet_test=wb_test.active
    for cellObj in sheet_test.columns[3]:
        print(cellObj.value)
        '''
     
    #打开处理的Excel
    wb=openpyxl.load_workbook('example.xlsx')  
    sheet=wb.active
    column=sheet.columns[2]
    column_C_num=len(column)  #4483个处理pdf
    column_C_num-=1            #去掉标题,要减一
     
    column_index=column_index_from_string('J') #J的索引号最终是10
    column_K=sheet.columns[column_index]   #要填写的K列
     
     
    column_J=sheet.columns[column_index-1]
    filenames_column_J=[]         #最终要填写的文件名集合
    for cellObj in column_J[1:]:   #console显示不全前面内容,出现第一项不是第一个
        #print(cellObj.value)
        filenames_column_J.append(cellObj.value)
        
    #Excel的J栏要处理pdf数量
    column_J_num=len(filenames_column_J)   #4483个处理pdf文档
     
    if column_C_num!=column_J_num:
        raise NameError
     
     
     
    #1.搜集所有pdf文档
    pdfFiles=[]
    for filename in os.listdir('.'):#返回当前文件夹的所有文件:
        if filename.endswith('.pdf'):
            pdfFiles.append(filename)
            
    pdfFile_num=len(pdfFiles)     #文件夹pdf数量
     
     
    #删除不需要的pdf文件
    for filename in pdfFiles:
        if filename not in filenames_column_J:
            os.remove(filename)
     
    #filename_error:Excel有的pdf文件,而路径找不到的pdf列表
    filename_error=[]  
    for i in filenames_column_J:
        if i not in pdfFiles:
            filename_error.append(i)
            
    #异常排除
    if filename_error!=[] or pdfFile_num!=column_J_num:
        raise NameError
     
    '''
    #当文件名由字母和数字组成时,文件路径排序会和Excel排序不一样
    for i in range(column_J_num):
        if pdfFiles[i]!=filenames_column_J[i]:  #审核文件名是否一致
            print ('wrongIndex:',i)
            raise NameError
    '''
     
     
     
    #需要对Excel的K行建立一个字典,方便找到索引
     
     
     
    #依次打开Excel对应的pdf文件名,写入cell
    loop=column_J_num  #循环次数要和文件名一致,1976及其之后的pdf,Python不能识别,只能处理到这一步
     
    for i in range(loop):
        #print ('file:',i)
        
        #每50行显示print
        if i%100==0:
            print ('fileindex:',i)
            
            
        filename=filenames_column_J[i]
        try:
            
            pdfFileObj=open(filename,'rb')
            pdfReader=PyPDF2.PdfFileReader(pdfFileObj)
        except:
            continue
        pages=pdfReader.numPages #显示页数
        #pageObj=pdfReader.getPage(0) #读取第一页的字符,第一页可读取
        #content=pageObj.extractText() #输出第一页字符
        
        #页面写入
        content=""
        for page in range(pages):
            try:
                pageObj=pdfReader.getPage(page) #读取第一页的字符,第一页可读取
                content+=pageObj.extractText() #输出第一页字符
            except:
                continue
                
        column_K[i+1].value=content        #不用转换,可直接写入excel,第二页pdf也可写入excel
        pdfFileObj.close()
     
    wb.save('example.xlsx') 
  • 相关阅读:
    第十篇 数据类型总结
    第九篇 字典类型的内置方法
    第二篇 输入与输出以及基础运算符
    <爬虫实战>糗事百科
    <读书笔记>如何入门爬虫?
    <读书笔记>001-以解决问题为导向的python编程实践
    <小白学技术>将python脚本导出为exe可执行程序
    <Django> 第三方扩展
    <Django> 高级(其他知识点)
    <Django> MVT三大块之Template(模板)
  • 原文地址:https://www.cnblogs.com/computerMatainance/p/5192909.html
Copyright © 2011-2022 走看看