【问题标题】:Issues converting xlsx to 2d array openpyxl将 xlsx 转换为二维数组 openpyxl 的问题
【发布时间】:2019-10-07 17:13:28
【问题描述】:

我有一个包含 2 列的 excel 电子表格,我正在尝试使用以下代码将其转换为二维数组:

#!/usr/bin/python3

import openpyxl
import sys
import os

book = openpyxl.load_workbook('contact2019.xlsx')

sheet = book.active


first_sheet = book.get_sheet_names()[0]
worksheet = book.get_sheet_by_name(first_sheet)
excel_data = [[0 for x in range(2)] for y in range(1)]

print(len(excel_data))
first = 0
cell_num = 0
for row in range(2,worksheet.max_row+1):
    for column in "AB":  #Here you can add or reduce the columns
        cell_name = "{}{}".format(column, row)
        excel_data.append(worksheet[cell_name].value)



print(excel_data)

我的问题是数据只是按顺序添加到一维数组中,所以我的输出如下:

['Sam Adams', '*******@gmail.com']

这不是我初始化的二维数组。

输入数据如下:

Sam Adams   **********@gmail.com
Sammy Adams **********@gmail.com
Samuel Adams    **********@gmail.com
Samantha Adams  **********@gmail.com
Sam Adams   **********@gmail.com

为什么这是顺序分配数据而不是每行两个?

【问题讨论】:

    标签: python arrays loops openpyxl xlsx


    【解决方案1】:

    或者:使用pandas:

    import pandas as pd
    import numpy as np
    
    df = pd.read_excel('test.xlsx')  # change the name of the file as needed
    
    # dataframe
               name                 email
          Sam Adams  **********@gmail.com
        Sammy Adams  **********@gmail.com
       Samuel Adams  **********@gmail.com
     Samantha Adams  **********@gmail.com
          Sam Adams  **********@gmail.com
    

    创建数组:

    excel_data = df.to_numpy()
    print(excel_data)
    
    # Output
    array([['Sam Adams', '**********@gmail.com'],
           ['Sammy Adams', '**********@gmail.com'],
           ['Samuel Adams', '**********@gmail.com'],
           ['Samantha Adams', '**********@gmail.com'],
           ['Sam Adams', '**********@gmail.com']], dtype=object)
    

    【讨论】:

    • 我会检查一下,在这种情况下,它没有太多数据或复杂,所以可能没有必要,但是当我遇到更复杂的数据集时肯定会使用它。
    【解决方案2】:

    欢迎来到 SO!

    您下面的代码会遍历并将每个项目添加为单独的项目,因此您可以按顺序获得所有内容。

    for row in range(2,worksheet.max_row+1):
        for column in "AB":  #Here you can add or reduce the columns
            cell_name = "{}{}".format(column, row)
            excel_data.append(worksheet[cell_name].value)
    

    您可以将代码替换为仅循环遍历行,而不是先循环遍历行然后遍历所有列。

    for row in range(2,worksheet.max_row+1):        
        excel_data.append([worksheet["A{}".format(row)].value,worksheet["B{}".format(row)].value])
    

    通过这样做,您现在正在创建一个包含 2 个元素列表(或 2d 数组)的列表。

    如果您不打算这样做,您还可以考虑使用 Python 库 pandas,它抽象了很多工作,并允许您使用名为 DataFrames 的电子表格类对象。

    【讨论】:

      猜你喜欢
      • 2017-09-04
      • 1970-01-01
      • 2019-01-23
      • 2020-03-26
      • 2012-08-15
      • 2021-01-31
      • 2016-02-18
      • 2018-02-19
      相关资源
      最近更新 更多