ValueError:无法转换为Excel

时间:2017-06-27 02:36:45

标签: python excel openpyxl

我正在尝试运行一个收集数据然后将其写入现有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]时,我已经开始工作了。

1 个答案:

答案 0 :(得分:1)

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

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

中偷走了逻辑