将 xlsx 转换为二维数组 openpyxl 的问题

Issues converting xlsx to 2d array openpyxl

我有一个包含 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

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

欢迎来到 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 个元素列表(或二维数组)的列表。

如果您不打算这样做,您还可以考虑 python 库 pandas,它抽象出大量工作并让您像使用名为DataFrames.

或者:使用 pandas:

  • 解决循环问题
  • 您可能会发现在 pandas
  • 中处理数据更容易
  • read_excel
  • to_numpy
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)