首页 > 解决方案 > 使用具有背景填充的单元格将列添加到列表

问题描述

我组织的成员希望能够对大型信息电子表格进行颜色编码,然后使用(使用 Openpyxl)Python 将其拉入系列列表,以插入 PowerPoint(使用 Python-pptx)。除了需要系列名称和系列数据(组织在可能不相邻的单独列中)的系列之外,我已经能够让一切正常工作。

这是我到目前为止所拥有的

        series_count = 2
        while series_count <= ws.max_column:
            for s in range(2, ws.max_column + 1):
                series_list = []                
                series_name = ws.cell(4, series_count).value
                for c in range(4, ws.max_row + 1):
                    cell = ws.cell(row = c, column = series_count)
                    if cell.value != series_name:
                        series_list.append(cell.value)
                chart_data.add_series(series_name, series_list, '0%') #Meant to take the series_name and series_list and create a chart using python-pptx
                series_count += 1

这仅抓取一个系列,并没有将其插入图表数据。我没有遇到任何异常,但打开 PowerPoint 文档时,只有空白图表字段。

如果数据在相邻列中,我可以手动设置范围,但从长远来看这是不可行的。

        series_count = 2
        while series_count <= ws.max_column:
            for s in range(2, ws.max_column + 1):
                series_list = []                
                series_name = ws.cell(4, series_count).value
                for c in range(4, ws.max_row + 1):
                    cell = ws.cell(row = c, column = series_count)
                    if cell.value != series_name:
                        series_list.append(cell.value)
                chart_data.add_series(series_name, series_list, '0%')
                series_count += 1

我是一个新手,所以我很高兴考虑其他方法来解决这个问题,这些方法可以在我的技术水平更低的同事的投入最少的情况下达到相同的结果。(他们可以管理颜色,但其他格式效果不佳。)

感谢您的帮助!

标签: pythonopenpyxlpython-pptx

解决方案


这段代码似乎对我有用。

    series_count = 2
    while series_count <= ws.max_column: #searches sheet for color-coded data and pulls it into series. 
        for s in range(2, ws.max_column + 1):
            series_list = []
            for c in range(4, ws.max_row + 1):
                cell = ws.cell(row = c, column = series_count)
                if cell.fill.start_color.index == 9:
                    series_list.append(cell.value)
                elif cell.fill.start_color.index == 8:
                    series_name = cell.value
                else:
                    pass
            if len(series_list) > 0:
                print "Adding", series_name, series_list
                chart_data.add_series(series_name, series_list, '0%')
            else:
                pass
            series_count += 1

感谢您的帮助!


推荐阅读