简体   繁体   English

如何将 Python 数组写入 Excel 电子表格

[英]How to write Python Array into Excel Spread sheet

I am trying to write following array into Excel spreadsheet using Python:我正在尝试使用 Python 将以下数组写入 Excel 电子表格:

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

At spreadsheet array should look:在电子表格数组应该看起来:

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

Is anyone can show some Python code to do it?有没有人可以展示一些 Python 代码来做到这一点? Thank you in advance,先感谢您,

Felix菲利克斯

Here is one way to do it using the XlsxWriter module:这是使用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()

Output:输出:

在此处输入图片说明

Use pandas data frame!使用熊猫数据框!

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 is File path in str or existing ExcelWriter object. excel_writer 是 str 或现有 ExcelWriter 对象中的文件路径。

The most common way that I've seen of writing to an excel spreadsheet with Python is by using OpenPyXL , a library non-native to python.我见过的使用 Python 写入 excel 电子表格的最常见方法是使用OpenPyXL ,这是一个非 Python 原生库。 Another that I've heard that is occasionally used is the XlsxWriter , again, though, it's non-native.我听说偶尔使用的另一个XlsxWriter ,但同样,它不是本地的。 Both sites have great documentation on how to best use the libraries but below is some simple code I wrote up to demonstrate OpenPyXL :这两个站点都有关于如何最好地使用这些库的很好的文档,但下面是我编写的一些简单代码来演示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)

EDIT: For example, your request could be written as such:编辑:例如,您的请求可以这样写:

## 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]

Honestly this might not even work but I'm too tired to test.老实说,这甚至可能不起作用,但我太累了无法测试。 I think you get the idea though.我想你明白了。

If you are already using pandas for your task, you can use it easily to create a dataframe and turn it into an Excel sheet.如果您已经在为您的任务使用Pandas ,您可以轻松地使用它来创建数据框并将其转换为 Excel 工作表。 If not, it is easier to use xlsxwriter rather than pandas because pandas is a little heavy library.如果没有,使用xlsxwriter比使用pandas更容易,因为 pandas 是一个有点重的库。

pip install XlsxWriter

import xlsxwriter

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

There are multiple ways to write the data to excel.有多种方法可以将数据写入excel。 You can use write_row(), write_column() or write cell by cell also.您也可以使用 write_row()、write_column() 或逐个单元格写入。

write_row(row, column, data) write_row(行,列,数据)

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

worksheet.write_row(1, 2, row)

write_column(row, column, data) write_column(行,列,数据)

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

worksheet.write_column(1, 2, column)

write(row, column, data)写(行,列,数据)

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

Finally, close the workbook.最后,关闭工作簿。

workbook.close()

Like this, there are many ways to write data and also you can conditional formatting to your cells or rows or columns.像这样,有很多方法可以写入数据,您也可以对单元格或行或列进行条件格式设置。 The documentation can be found here .文档可以在这里找到。

print array

This prints the array in the Python console with square brackets marking the beginning and end of rows.这将在 Python 控制台中打印数组,并用方括号标记行的开头和结尾。 Select the whole of that and copy-paste to Excel.选择整个并复制粘贴到 Excel。 Click on the paste icon -> Text Import Wizard.单击粘贴图标 -> 文本导入向导。 That should bring up this .那应该提出这个

Choose Fixed Width and click Next to get this选择固定宽度,然后单击下一步得到这个

Click Next and click Finish.单击下一步,然后单击完成。 That will do it.这样就可以了。 You'll still need to delete the ending brackets from some of the cells.您仍然需要从某些单元格中删除结束括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM