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

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

不幸的是,在我运行这个脚本之后,尽pipe它能正常工作,并且我已经在单元格中复制了所需的值,出于某种原因,图表消失了。 我还没有设法理解为什么,给我的事实,我没有任何暗示在我的脚本中操纵图表的工作。

看到我找不到解决这个问题的办法,我得出的结论是,我应该使用我所拥有的价值观来实现我脚本中的图表。 不过,我想知道你是否知道为什么会发生这种情况。

以下是我的代码。 我不得不提到我是Python新手。 任何关于这个问题或关于更好的代码写作的build议将不胜感激。

# -*- 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]) 

我已经能够重新创build你的问题。 使用openpyxl简单地加载和保存一个现有的xlsx文件后,我的图表丢失了,没有做任何改变。

不幸的是,根据openpyxl的文档 :

警告

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

它确实支持创build有限的图表:

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

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