ValueError: Cannot Convert to Excel

ValueError: Cannot Convert to Excel

我正在尝试 运行 一个收集数据然后将其写入现有 excel 文件的程序。我 运行 遇到了一个意想不到的问题。我的代码如下:

import good_morning as gm
import numpy
fd = gm.FinancialsDownloader()
fd_frames = fd.download('AAPL')
wb = UpdateWorkbook(r'C:\Users\vince\Project\Spreadsheet.xlsx', worksheet=1)
df_2 = fd_frames['income_statement']
df_2.set_index('title', inplace=True)
df_2 = df_2.drop('parent_index', axis=1)
df_2 = df_2.loc[['Revenue','Operating expenses']] #Add all the names you   want from income statement
df_2 = df_2/(10**9)
wb['M6:N6'] = df_2.values
wb.save()

这是 df_2.values 的输出:

array([[ 156.508,  170.91 ,  182.795,  233.715,  215.639,  220.457],
   [  13.421,   15.305,   18.034,   22.396,   24.239,   25.364]])

我不断收到一条错误消息:

ValueError: Cannot convert [ 156.508  170.91   182.795  233.715  215.639  220.457] to Excel

我只是想将这些值写入特定的单元格。我非常接近完成该项目,但 运行 陷入了这个意外错误。有谁知道如何解决这个问题?任何帮助是极大的赞赏。谢谢

这是我的其余代码:

class UpdateWorkbook(object):
    def __init__(self, fname, worksheet=0):
        self.fname = fname
        self.wb = load_workbook(fname)
        self.ws = self.wb.worksheets[worksheet]

    def save(self):
        self.wb.save(self.fname)

    def __setitem__(self, _range, values):
    """
     Assign Values to a Worksheet Range
    :param _range:  String e.g ['M6:M30']
    :param values: List: [row 1(col1, ... ,coln), ..., row n(col1, ... ,coln)]
    :return: None
    """

        def _gen_value():
            for value in values:
                yield value

            if not isinstance(values, (list, numpy.ndarray)):
                raise ValueError('Values Type Error: Values have to be "list": values={}'.
                                  format(type(values)))
            if isinstance(values, numpy.ndarray) and values.ndim > 1:
                raise ValueError('Values Type Error: Values of Type numpy.ndarray must have ndim=1; values.ndim={}'.
                              format(values.ndim))

        from openpyxl.utils import range_boundaries
        min_col, min_row, max_col, max_row = range_boundaries(_range)
        cols = ((max_col - min_col)+1)
        rows = ((max_row - min_row)+1)
        if cols * rows != len(values):
        raise ValueError('Number of List Values:{} does not match Range({}):{}'.
                         format(len(values), _range, cols * rows))

        value = _gen_value()
        for row_cells in self.ws.iter_rows(min_col=min_col, min_row=min_row,
                                       max_col=max_col, max_row=max_row):
            for cell in row_cells:
                cell.value = value.__next__()

电子表格中的内容比较复杂,我只需要替换电子表格中已有的数据即可。上面的代码应该可以做到。每当我使用 loc 时,我都会 运行 陷入那个错误。当我设置 wb['M6:N6'] = df_2.values[0] 时,我已经让它工作了。

尝试用这个嵌套的 for 循环替换行 wb['M6:N6'] = df_2.values

r = 1  # start at first row
c = 13 # column 'M'
for l in df_2.values.tolist():
    for item in l:
        wb.ws.cell(row=r, column=c).value = item
        c += 1 # Column 'N'
    c = 13
    r += 1

看看它是否有效。

我偷了这个答案的逻辑How to write a list to xlsx using openpyxl