python编辑excel做报表给manager看

import xlrd
import os
import re
from numpy import arange
import zipfile
import matplotlib.pyplot as plt
import re



def read_excel_make_picture(file):
    workbook = xlrd.open_workbook(file)
    mySheet = workbook.sheet_by_index(0)
    filename = os.path.basename(file)
    counter_dict_by_mo_id = dict()
    # 获取文件中的时间数据
    times = workbook.sheet_by_index(0).row_values(0)
    times.pop(0)
    #画图取得不同颜色的数组
    color_sequence = ['#1f77b4', '#aec7e8', '#ff7f0e', '#ffbb78', '#2ca02c',
                      '#98df8a', '#d62728', '#ff9896', '#9467bd', '#c5b0d5',
                      '#8c564b', '#c49c94', '#e377c2', '#f7b6d2', '#7f7f7f',
                      '#c7c7c7', '#bcbd22', '#dbdb8d', '#17becf', '#9edae5']

    i = 0
    # 循环分析excel中的每个sheet
    for table in workbook.sheets():
        # 获取此sheet的mo
        mo = table.cell_value(0, 0)
        counter_dict_by_mo_id[mo] = dict()
        # 获取此sheet中包含的kpi
        keys = table.col_values(0)
        keys.pop(0)
        i += 1
        plt.figure(i)
        # 循环获取每个kpi的具体数值
        for index, key in enumerate(keys):
            data = table.row_values(index + 1)
            data.pop(0)
            counter_dict_by_mo_id[mo][key] = data
            # 读取sheets名字
            count1 = len(workbook.sheets())
        # 这里需要加一个正则表达式一个是对时间正则
        reobj = re.compile(r'LR\d+_D\d+_E\d+')
        count = counter_dict_by_mo_id[mo]

        # 获取时间信息
        temp_times = []
        for time in times:
            temp_times.append(time[20:26] + '+' + time[35:39])
        #print(temp_times)
        #figures取得是excel的count值
        figures = []
        for figure in keys:
            figures.append(figure[:])
        #获取几个count
        x_label = len(figures)
        # 此处应该加一个循环获取figures的长度,根据长度设置子图,已加
        figures_xnumber = []
        for figures_number in count.values():
            # print(figures_number)
            figures_xnumber.append(figures_number[:])
            # print(figures_xnumber[0])
        y1 = temp_times[:]
        x1 = arange(len(temp_times))
        #设置图片的大小
        fig=plt.figure(figsize=(20,10))
        #循环取数
        for x_number in arange(x_label):
            # print(x_number)
            ax = plt.subplot(x_label, 1, x_number + 1)
            if x_number==0:
                ax.set_title('kpi' + mo)
            RGB_number=x_number%len(color_sequence)
            RGB_color=color_sequence[RGB_number]
            ax.plot(figures_xnumber[x_number],linewidth=1,color=RGB_color, label=figures[x_number],  ls=':', marker='o')
            # print(len(figures))
            # print(figures[0])
            box = ax.get_position()
            ax.legend(loc='upper right')
            #判断x轴长度
            if len(temp_times)%2==0:
                cut_picutre=len(temp_times)/2
            elif len(temp_times)%2==1:
                cut_picutre=len(temp_times)/2 - 1/2
            ax.axvline(cut_picutre, color='black')
            plt.xticks(arange(len(temp_times)), temp_times[:], color='black', rotation=40)
        #保存文件

        file_name = ('kpi' + '_' + mo).replace('.', '_') + '.png'
        plt.savefig(r'E:\test\\'+file_name, format='png')
        print(file_name + ' saved.')
        plt.close()
        zipAllPngFiles("E:\\test",filename)
        # temp_times.pop(0)

    #plt.show()



def zipAllPngFiles(inputFolder,filename):#打包项目文件
    res_name = os.path.join(inputFolder, filename+'.zip')
    f = zipfile.ZipFile(res_name, 'w', zipfile.ZIP_DEFLATED)
    for file in os.listdir(inputFolder):
        if file.endswith('.png'):
            f.write(os.path.join(inputFolder, file), file)
    f.close()
    print('********** zip all png files done !!   **********')

excel = r'E:\kpi_LR16_Avg_UL_Noise_per_PRB_Grp_01_OTH_addNOK_001a_dBm.xls'

print(read_excel_make_picture(excel))



### 回答1: 可以使用Python中的第三方库,例如tabula-py或pdfminer来将PDF表格转换为Excel格式。使用这些库,你可以将PDF文件中的表格提取出来,并将其保存为Excel文件。具体的实现方法可以参考相关的文档和教程。 ### 回答2: Python可以通过使用pdfminer或PyPDF2库来读取pdf文件中的表格数据,并使用pandas库将表格数据转换为Excel文件。 首先,我们需要安装必要的库。使用以下命令在命令行或终端中安装所需库: ``` pip install pdfminer.six pip install PyPDF2 pip install pandas ``` 接下来,我们可以使用pdfminer库来提取pdf文件中的表格数据。以下是一个示例代码片段: ```python from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LAParams, LTTextBox, LTTextLine from pdfminer.pdfinterp import PDFPageInterpreter, PDFResourceManager from pdfminer.pdfpage import PDFPage def extract_table_data_from_pdf(file_path): # 创建一个PDF资源管理器对象并设置参数 resource_manager = PDFResourceManager() laparams = LAParams() device = PDFPageAggregator(resource_manager, laparams=laparams) # 创建一个PDF解释器对象 interpreter = PDFPageInterpreter(resource_manager, device) table_data = [] # 打开pdf文件 with open(file_path, 'rb') as file: # 遍历pdf页面 for page in PDFPage.get_pages(file): # 解释器处理页面 interpreter.process_page(page) # 获取页面布局 layout = device.get_result() # 遍历页面布局中的所有元素 for element in layout: # 如果元素是文本框或文本行 if isinstance(element, (LTTextBox, LTTextLine)): # 获取元素的文本 text = element.get_text().strip() # 如果文本以水平制表符分隔,将其分割为一个表格行 if '\t' in text: row = text.split('\t') table_data.append(row) return table_data # 从pdf文件中提取表格数据 pdf_file_path = 'example.pdf' table_data = extract_table_data_from_pdf(pdf_file_path) ``` 然后,我们可以使用pandas库将表格数据转换为Excel文件。以下是一个示例代码片段: ```python import pandas as pd # 将表格数据转换为pandas的DataFrame对象 df = pd.DataFrame(table_data) # 将DataFrame数据保存为Excel文件 excel_file_path = 'example.xlsx' df.to_excel(excel_file_path, index=False) ``` 通过以上步骤,我们可以将pdf文件中的表格数据转换为Excel文件。请注意,这只适用于提取包含文本的简单表格,不适用于提取包含图像或复杂排版的表格。 ### 回答3: Python 中有多种库可以用于将 PDF 表格转换为 Excel,其中比较常用的库是 `tabula-py` 和 `camelot-py`。 1. `tabula-py` 是一个基于 Java 的库,可以通过调用 Java 的 `tabula-java` 实现 PDF 表格的提取。使用这个库,你需要先安装 Java 环境,并在 Python 中安装 `tabula-py` 库。然后,你可以使用 `tabula-py` 提供的函数来提取指定的 PDF 表格,并将其保存为 Excel 文件。 2. `camelot-py` 是一个基于 Python 的 PDF 表格提取库。使用这个库,你可以直接在 Python 中提取 PDF 表格,并将其保存为 Excel 文件。你需要先安装 `camelot-py` 库,并导入相应的模块。然后,你可以使用 `camelot-py` 提供的函数来提取指定的 PDF 表格,并转换为 Pandas 的数据框,最后可以将数据框保存为 Excel 文件。 总结起来,使用 Python 将 PDF 表格转为 Excel 可以借助 `tabula-py` 或 `camelot-py` 这两个库来实现。具体的步骤是通过调用相应的函数或方法来提取 PDF 表格,并保存为 Excel 文件。这些库都有详细的文档和示例代码可供参考,你可以根据自己的需求选择适合的方法进行操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值