how to write python array (data = []) to excel?

空扰寡人 提交于 2020-01-13 02:14:54

问题


I am writing a python program to process .hdf files, I would like to output this data to an excel spreadsheet. I put the data into an array as shown below:

Code:

data = []

for rec in hdfFile[:]:
    data.append(rec)

from here I have created a 2D array with 9 columns and 171 rows.

I am looking for a way to iterate through this array and write each entry in order to a sheet. I am wondering if If I should create a list instead, or how to do this with the array I have created.

Any help would be greatly appreciated.


回答1:


A great file type to be aware of is a CSV, or Comma Separated Value file. It's a very simple text file type (normally already associated with Excel or other spreadsheet apps) where each comma separates multiple cells on the same row and each new line in the file represents data on a new row. I.E.:

A,B,C
1,2,3
"Hello, World!"

The above example would result in the first row having 3 cells, each cell holding each letter. The new line states that 1, 2, and 3 are in the next row, each in their own cell. If a cell needs a comma in it, you can place that cell in quotes. In my example, "Hello, World!" would exist in the 3rd row, 1st cell. For a more formal definition: http://www.csvreader.com/csv_format.php




回答2:


Just like @senderle said, use csv.writer

a = [[1,2,3],[4,5,6],[7,8,9]]
ar = array(a)

import csv

fl = open('filename.csv', 'w')

writer = csv.writer(fl)
writer.writerow(['label1', 'label2', 'label3']) #if needed
for values in ar:
    writer.writerow(values)

fl.close()    



回答3:


The built-in solution is python's csv module. You can create a csv.writer and use that to append rows to a .csv file, which can be opened in excel.



来源:https://stackoverflow.com/questions/6190612/how-to-write-python-array-data-to-excel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!