Python 脚本错误地删除了 .xlsx 文件中创建的图表

2024-02-28

我尝试使用 Python 编写一个脚本,该脚本从存储在文件夹层次结构中的所有 .csv 文件中获取一些特定值。这些值将复制到已创建的目标文件 (.xlsx) 中的某些特定单元格。目标文件还有一些现有的空图表(在单独的工作表中),这些图表将使用脚本提供的值进行填充。

不幸的是,在我运行脚本后,尽管它有效并且我在单元格中复制了所需的值,但由于某种原因,图表消失了。我还没有设法理解为什么,因为我没有使用任何暗示在我的脚本中操作图表的东西。

看到我找不到这个问题的任何解决方案,我得出的结论是,我应该使用我拥有的值在脚本中实现图表的绘制。但是,我想知道您是否知道为什么会发生这种情况。

下面是我的代码。我不得不提一下,我是 Python 新手。 任何有关该问题或更好编写代码的建议将不胜感激。

# -*- coding: utf-8 -*-

import os
import glob
import csv
import openpyxl
from openpyxl import load_workbook

#getting the paths
def get_filepaths(directory):

    file_paths = []  # array that will contain the path for each file

    # going through the folder hierarchy
    for root, directories, files in os.walk(directory):
        for filename in files:
            if filename.endswith('.csv'): 
                filepath = os.path.join(root, filename) #concatenation
                file_paths.append(filepath)  # filling the array
                print filepath
                #print file_paths[0]

    return file_paths  


#extraction of the value of interest from every .csv file   
def read_cell(string, paths):
    with open(paths, 'r') as f:
        reader = csv.reader(f)        
        for n in reader:            
            if string in n:             
                cell_value = n[1]
                return cell_value



#array containing the path extracted for each file    
paths_F = get_filepaths('C:\Dir\mystuff\files')      

#destination folder
dest = r'C:\Dir\mystuff\destination.xlsx'   

#the value of interest 
target = "something"        

#array that will contain the value for each cell    
F30 = [];     

#obtaining the values    
for selection_F in paths_F:         
        if '30cm' in selection_CD:
            val_F30 = read_cell(target, selection_F);      F30.append(val_F30)
            #print val_F30


wb = load_workbook(dest)

#the sheet in which I want to write the values extracted from the files
ws3EV = wb.get_sheet_by_name("3EV")

   cell_E6 = ws10EV.cell( 'E6' ).value = int(F30[0])
cell_E7 = ws10EV.cell( 'E7' ).value = int(F30[1])

我已经能够重现您的问题。使用 openpyxl 简单地加载并保存现有 xlsx 文件后,我的图表在没有进行任何更改的情况下丢失了。

不幸的是,根据openpyxl 的文档 https://openpyxl.readthedocs.org/en/latest/charts.html#charts:

Warning

Openpyxl 目前仅支持在工作表中创建图表。 现有工作簿中的图表将丢失。

但它确实支持创建有限数量的图表:

  • 条形图
  • 折线图
  • 散点图
  • 饼形图

您可以使用这些重新创建所需的图表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 脚本错误地删除了 .xlsx 文件中创建的图表 的相关文章

随机推荐