Skip to main content
 首页 » 编程设计

python之无法使用openpyxl保存excel文件

2025年05月04日7softidea

我在 openpyxl 中保存 Excel 文件时遇到问题。 我正在尝试创建一个处理脚本,该脚本将从一个 excel 文件中获取数据,将其转储到一个转储 excel 文件中,然后在对 excel 中的公式进行一些调整之后,我将在转储 excel 文件中拥有所有处理过的数据。我当前的代码是这样的。

from openpyxl import load_workbook 
import os 
import datetime 
from openpyxl.cell import get_column_letter, Cell, column_index_from_string, coordinate_from_string 
 
dump = dumplocation 
desktop = desktoplocation 
date = datetime.datetime.now().strftime("%Y-%m-%d") 
 
 
excel = load_workbook(dump+date+ ".xlsx", use_iterators = True) 
 
sheet = excel.get_sheet_by_name("Sheet1") 
 
try: 
    query = raw_input('How many rows of data is there?\n') 
except ValueError: 
    print 'Not a number' 
 
#sheetname = raw_input('What is the name of the worksheet in the data?\n') 
for filename in os.listdir(desktop): 
    if filename.endswith(".xlsx"): 
        print filename 
 
        data = load_workbook(filename, use_iterators = True) 
        ws = data.get_sheet_by_name(name = '17270115') 
 
    #copying data from excel to data excel 
        n=16 
        for row in sheet.iter_rows(): 
            for cell in row: 
                for rows in ws.iter_rows(): 
                    for cells in row: 
                        n+=1 
                        if (n>=17) and (n<=32): 
                            cell.internal_value = cells.internal_value 
 
 
    #adding column between time in UTC and the data 
        column_index = 1 
        new_cells = {} 
        sheet.column_dimensions = {} 
        for coordinate, cell in sheet._cells.iteritems(): 
            column_letter, row = coordinate_from_string(coordinate) 
            column = column_index_from_string(column_letter) 
 
    # shifting columns 
            if column >= column_index: 
                column += 1 
 
            column_letter = get_column_letter(column) 
            coordinate = '%s%s' % (column_letter, row) 
 
    # it's important to create new Cell object 
            new_cells[coordinate] = Cell(sheet, column_letter, row, cell.value) 
 
        sheet.cells = new_cells 
    #setting columns to be hidden 
        for coordinate, cell in sheet._cells.iteritems(): 
            column_letter, row = coordinate_from_string(coordinate) 
            column = column_index_from_string(column_letter) 
 
            if (column<=3) and (column>=18): 
               column.set_column(column, options={'hidden': True}) 

自从我两三周前才开始使用 Python 以来,我知道我的很多代码都很困惑。我还有一些悬而未决的问题,稍后可以处理。 似乎没有很多人出于我的目的使用 openpyxl。 我尝试使用普通的 Workbook 模块,但这似乎不起作用,因为您无法在单元格项目中进行迭代。 (我需要将相关数据从一个 excel 文件复制并粘贴到另一个)

更新:我意识到 openpyxl 只能创建工作簿但不能编辑当前工作簿。所以我决定在将数据传输到新工作簿后改变曲调并编辑它。我已经使用 back to Workbook 来传输数据:

from openpyxl import Workbook 
from openpyxl import worksheet 
from openpyxl import load_workbook 
import os 
from openpyxl.cell import get_column_letter, Cell, column_index_from_string, coordinate_from_string 
 
dump = "c:/users/y.lai/desktop/data/201501.xlsx" 
desktop = "c:/users/y.lai/desktop/" 
 
 
 
excel = Workbook() 
 
sheet = excel.add_sheet 
 
try: 
    query = raw_input('How many rows of data is there?\n') 
except ValueError: 
    print 'Not a number' 
 
#sheetname = raw_input('What is the name of the worksheet in the data?\n') 
for filename in os.listdir(desktop): 
    if filename.endswith(".xlsx"): 
        print filename 
 
        data = load_workbook(filename, use_iterators = True) 
        ws = data.get_sheet_by_name(name = '17270115') 
 
    #copying data from excel to data excel 
        n=16 
        q=0 
        for x in range(6,int(query)): 
            for s in range(65,90):    
                for cell in Cell(sheet,chr(s),x): 
                    for rows in ws.iter_rows(): 
                        for cells in rows: 
                            q+=1 
                            if q>=5: 
                                n+=1 
                                if (n>=17) and (n<=32): 
                                    cell.value = cells.internal_value 

但是这个好像还是不行

    Traceback (most recent call last): 
      File "xxx\Desktop\xlspostprocessing.py", line 40, in <module> 
    for cell in Cell(sheet,chr(s),x): 
      File "xxx\AppData\Local\Continuum\Anaconda\lib\site-packages\openpyxl\cell.py", line 181, in __init__ 
    self._shared_date = SharedDate(base_date=worksheet.parent.excel_base_date) 
    AttributeError: 'function' object has no attribute 'parent' 

浏览了 API,但是...我被其中的编码弄得不知所措,所以我无法理解 API。在我看来,我似乎错误地使用了 Cell 模块。我阅读了 Cell 的定义及其属性,因此得到了 26 个字母 A-Z 的 chr(s)。

请您参考如下方法:

您可以使用标准工作簿模式进行迭代。 use_iterators=True 已重命名为 read_only=True 以强调此模式的用途(按需读取部分)。

您的代码目前无法使用此方法,因为工作簿是只读的,并且 cell.internal_value 始终是只读属性。

但是,由于您的 Excel 文件存在问题,您似乎还没有完成。您可能想提交其中一个文件的错误。邮件列表也可能是更好的讨论场所。