如何将 Python 数组写入 Excel Spread sheet

How to write Python Array into Excel Spread sheet

我正在尝试使用 Python 将以下数组写入 Excel 电子表格:

array = [ [a1,a2,a3], [a4,a5,a6], [a7,a8,a9], [a10, a11, a12, a13, a14]]

电子表格数组应如下所示:

a1  a4  a7  a10
a2  a5  a8  a11
a3  a6  a9  a12
            a13
            a14

有没有人可以展示一些 Python 代码来做到这一点? 提前谢谢你,

菲利克斯

我见过用 Python 写入 excel 电子表格的最常见方法是使用 OpenPyXL, a library non-native to python. Another that I've heard that is occasionally used is the XlsxWriter, again, though, it's non-native. Both sites have great documentation on how to best use the libraries but below is some simple code I wrote up to demonstrate OpenPyXL:

from openpyxl import workbook
from openpyxl.cell import get_column_letter

workbook = Workbook() # the master workbook
output_file_name = "outfile.xlsx" # what "workbook" will be saved as

worksheet = workbook.active() # all workbooks have one worksheet already selected as the default
worksheet.title = "foo"

worksheet['A3'] = "=SUM(A1, A2)" # set up basic formula
wb.save(output_file_name)

编辑: 例如,您的请求可以这样写:

## imports and stuff ##
array = [ [a1,a2,a3], [a4,a5,a6], [a7,a8,a9], [a10, a11, a12, a13, a14]]

workbook = Workbook()
worksheet = workbook.active()

numrows = len(array)
letter = 'A'
for r in range(0, numrows):
    if r == 0: letter = 'A'
    if r == 1: letter = 'B'
    if r == 2: letter = 'C'
    ...

    numcols = len(array[r])
    for c in range(0, numcols):
        worksheet[letter.join(c)] = array[r][c]

老实说,这甚至可能行不通,但我太累了,无法测试。我想你明白了。

这是使用 XlsxWriter 模块的一种方法:

import xlsxwriter

workbook = xlsxwriter.Workbook('arrays.xlsx')
worksheet = workbook.add_worksheet()

array = [['a1', 'a2', 'a3'],
         ['a4', 'a5', 'a6'],
         ['a7', 'a8', 'a9'],
         ['a10', 'a11', 'a12', 'a13', 'a14']]

row = 0

for col, data in enumerate(array):
    worksheet.write_column(row, col, data)

workbook.close()

输出:

print array

这会在 Python 控制台中打印数组,方括号标记行的开头和结尾。 Select 全部复制粘贴到 Excel。单击粘贴图标 -> 文本导入向导。那应该会出现 this.

选择固定宽度点击下一步得到this

单击“下一步”,然后单击“完成”。这样就可以了。您仍然需要删除某些单元格的结尾括号。

使用pandas数据框!

import pandas as pd

array = [['a1', 'a2', 'a3'],
         ['a4', 'a5', 'a6'],
         ['a7', 'a8', 'a9'],
         ['a10', 'a11', 'a12', 'a13', 'a14']]

df = pd.DataFrame(array).T
df.to_excel(excel_writer = "C:/Users/Jing Li/Desktop/test.xlsx")

excel_writer 是 str 或现有 ExcelWriter 对象中的文件路径。

如果您已经在使用 pandas 来完成您的任务,您可以轻松地使用它来创建数据框并将其转换为 Excel sheet。如果没有,使用 xlsxwriter 比 pandas 更容易,因为 pandas 是一个有点重的库。

pip install XlsxWriter

import xlsxwriter

workbook = xlsxwriter.Workbook("MyExcel.xlsx")
worksheet = workbook.add_worksheet()

有多种方法可以将数据写入excel。您也可以使用 write_row()、write_column() 或逐个单元格地写入。

write_row(行、列、数据)

row = [1, 2, 3, 4, 5]

worksheet.write_row(1, 2, row)

write_column(行、列、数据)

column= [1, 2, 3, 4, 5]

worksheet.write_column(1, 2, column)

写入(行、列、数据)

worksheet.write(0, 1, "Hello")
worksheet.write(0, 2, "World")

最后,关闭工作簿。

workbook.close()

像这样,有很多方法可以写入数据,您还可以对单元格或行或列进行条件格式化。可以找到文档 here