Skip to main content
 首页 » 编程设计

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

2024年10月24日14jpfss

我尝试使用 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 文件后,我的图表没有做任何更改就丢失了。

不幸的是,根据documentation for openpyxl :

Warning

Openpyxl currently supports chart creation within a worksheet only. Charts in existing workbooks will be lost.

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

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

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