【问题标题】:Can't save excel file using openpyxl无法使用openpyxl保存excel文件
【发布时间】:2015-01-29 05:38:46
【问题描述】:

我在 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 的定义及其属性,因此有 chr(s) 来给出 26 个字母 A-Z。

【问题讨论】:

  • openpyxl 可以编辑现有工作簿,但如果您以只读模式打开它们,则不能。此讨论现已移至邮件列表。
  • @CharlieClark 我在保存时遇到了麻烦,即使我不是只读的stackoverflow.com/questions/31237229/…。不幸的是,无法读取 Excel 日志文件。知道可能是什么问题吗?无论我尝试保存到新工作簿还是已加载的工作簿,都会发生这种情况。
  • @CharlieClark Windows 上的另一个保存问题,这次是绝对文件名和包裹在 r'' 中的文件名:stackoverflow.com/questions/31362887/…

标签: python excel openpyxl


【解决方案1】:

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

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

但是,您的 Excel 文件存在问题,您似乎还没有走那么远。您可能希望提交其中一个文件的错误。此外,邮件列表可能是一个更好的讨论场所。

【讨论】:

  • 所以对于我的代码来说,问题是我写的那个是“只读的”? (即在我的代码中表现出色)+这很难,因为数据采用 .tst 格式,我在执行此过程之前手动对其进行分隔,似乎在我应用代码后文件已损坏感谢您的帮助:)跨度>
【解决方案2】:

您可以尝试使用 xlrd 和 xlwt 代替 pyopenxl,但您可能会发现 xlutil 中已经提供了您想要做的事情 - 所有这些都来自 python-excel。

【讨论】:

  • 您无法使用 Python Excel 创建 Excel 2010 文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多