在Python中将列表保存到excel

lbsnaicq  于 2023-02-20  发布在  Python
关注(0)|答案(2)|浏览(149)

我的列表中包含不同数量的变量。当我想以列表形式保存到Excel时,它保存到Excel,但当我查询Excel中的单元格时,我看到它保存为字符串,而不是列表。
有什么解决办法吗?还是我看问题的Angular 错了?
有了下面的代码,我的意思会更好地理解。

import streamlit as st
import pandas as pd

df_path = 'database/meters_try.xlsx'
df = pd.read_excel(df_path)

a = ['2023-02-11']
b = 'PR'
c = ['A', 'B']
d = 'AAA'
e = 'SHIFT'
f = ['PERSON1', 'PERSON2']
g = ['PERSON3', 'PERSON4', 'PERSON5']
h = ['QQ']
i = ['0']
j = ['50', '110']
k = ['50', '60',]
l = 'NOTES.'

b_type = type(b)
st.write(b_type)

c_type = type(c)
st.write(c_type)


def add_data(a, b, c, d, e, f, g, h, i, j, k, l, df):
    temp_df = pd.DataFrame({
    "column1": [a],
    "column2": [b],
    "column3": [c],
    "column4": [d],
    "column5": [e],
    "column6": [f],
    "column7" : [g],
    "column8": [h],
    "column9": [i],
    "column10": [j],
    "column11": [k],
    "column12": [l]
    })
    df_meters = pd.read_excel(df_path)
    df_meters = df_meters.append(temp_df, ignore_index=True)
    df_meters.to_excel(df_path, index=False)
    st.write(df_meters)

button = st.button("Save!")
if button:
    add_data(a, b, c, d, e, f, g, h, i, j, k, l, df)
    st.success("Saved")



def find_column_data_type(df):
    for col in df.columns:
        col_type = type(df[col][0])
        st.write(f"{col} column data type: {col_type}")

if st.button("Find the columns data type"):
    find_column_data_type(df)
nhn9ugyo

nhn9ugyo1#

我猜Excel不知道什么是Python列表。
在你看完excel之后,你可以使用eval把它转换回一个列表:

import pandas as pd
file = "/home/bera/Desktop/testexcel.xlsx"
df = pd.DataFrame(data={'A':[[1,2,3], [4,5,6]]})
#     A
# [1, 2, 3]
# [4, 5, 6]

#type(df.iloc[0]["A"])
#list

df.to_excel(file, index=False)

df2 = pd.read_excel(file)
#     A
# [1, 2, 3]
# [4, 5, 6]

#type(df2.iloc[0]["A"])
#str #Now it's a string

df2["A"]= df2["A"].map(eval)
# df2.iloc[0]["A"])
# list
6jjcrrmo

6jjcrrmo2#

将列表作为单独的单元格而不是字符串保存到Excel的一种方法是使用Python库,如openpyxl。
下面是演示如何将列表列表保存到Excel文件的示例代码:

import openpyxl

# create a workbook object
workbook = openpyxl.Workbook()

# select the active worksheet
worksheet = workbook.active

# sample list of lists
data = [[1, 2, 3], [4, 5, 6, 7], [8, 9]]

# write the data to the worksheet
for row in data:
    worksheet.append(row)

# save the workbook to a file
workbook.save("data.xlsx")

相关问题