如何使用python将列表列表写入Excel?

时间:2019-04-04 05:12:16

标签: python excel python-3.x

  

如何使用python 3将列表列表写入Excel?

new_list = [["first",second"],["third',four"]]
with open("file_name.csv", 'w') as f:
    fc = csv.writer(f, lineterminator='\n')
    fc.writerows(new_list)
  

现在我将此列表写入csv文件,但我想在Excel文件中写入   怎么样?

5 个答案:

答案 0 :(得分:1)

我认为您应该使用pandas库在该库中写入和读取数据,函数pandas.DataFrame.to_excel(..)将使您能够直接写入excel文件,而您可能需要定义{{3 }},这是dataCamp在熊猫数据帧上的pandas.DataFrame

答案 1 :(得分:1)

您尝试以下代码:

import pandas as pd

new_list= [["first","second"],["third","four"],["five","six"]] 
df = pd.DataFrame(new_list)
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer,sheet_name='welcome',index=False)
writer.save()

答案 2 :(得分:0)

import pyexcel

# Get the data
new_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Save the array to a file
pyexcel.save_as(array=new_list, dest_file_name="array_data.xls")


# Retrieve the records of the file
# records = pyexcel.get_records(file_name="test.xls")

# Get an array from the data
# my_array = pyexcel.get_array(file_name="test.xls")

# Get your data in a dictionary of 2D arrays
# 2d_array_dictionary = pyexcel.get_book_dict(file_name="test.xls")

# The data
# 2d_array_dictionary = {'Sheet 1': [
                               ['ID', 'AGE', 'SCORE']
                               [1, 22, 5],
                               [2, 15, 6],
                               [3, 28, 9]
                              ],
                   'Sheet 2': [
                                ['X', 'Y', 'Z'],
                                [1, 2, 3],
                                [4, 5, 6]
                                [7, 8, 9]
                              ],
                   'Sheet 3': [
                                ['M', 'N', 'O', 'P'],
                                [10, 11, 12, 13],
                                [14, 15, 16, 17]
                                [18, 19, 20, 21]
                               ]}

  # Save the data to a file                        
  # pyexcel.save_book_as(bookdict=2d_array_dictionary, dest_file_name="2d_array_data.xls")

答案 3 :(得分:0)

这是使用XlsxWriter的一种方法:

import xlsxwriter

new_list = [['first', 'second'], ['third', 'four'], [1, 2, 3, 4, 5, 6]]

with xlsxwriter.Workbook('test.xlsx') as workbook:
    worksheet = workbook.add_worksheet()

    for row_num, data in enumerate(new_list):
        worksheet.write_row(row_num, 0, data)

输出:

enter image description here

答案 4 :(得分:0)

我认为最方便的方法是在熊猫中使用Series。

import pandas as pd

new_list =['whatever']
pd.Series(new_list)
new_list.to_excel('aFileName.xlsx')