简体   繁体   English

将 Python 列表变量复制到现有的 xlsx excel 文件中

[英]Copy Python list variable into existing xlsx excel file

I'm new to Python, so please excuse my ignorance.我是 Python 新手,请原谅我的无知。 I have tried several different bits of code using openpyxl and pandas, however, can't get anything to work.我已经使用 openpyxl 和 pandas 尝试了几种不同的代码,但是,无法使任何工作正常进行。

What I need is to copy the text of an existing list-variable in Python (which is an array of file paths), and paste this into an existing xlsx worksheet at a given cell.我需要的是复制 Python 中现有列表变量的文本(它是一个文件路径数组),并将其粘贴到给定单元格的现有 xlsx 工作表中。

For example, given the list-variable in Python ["apple", "orange", "grape"], I need cells A2, A3, and A4 of Sheet 1 to read the same.例如,给定 Python 中的列表变量 ["apple", "orange", "grape"],我需要工作表 1 的单元格 A2、A3 和 A4 来读取相同的内容。 Any help is much appreciated!任何帮助深表感谢!

import pandas as pd
import os

folder = "C:\\Users\\user\\Documents\\temp"
x = []
for path in os.listdir(folder):
if path.endswith(".png"):
    full_path = os.path.join(folder, path)
    x.append(full_path)

fn = r"C:\\Users\\user\\Documents\\test.xlsx"
df = pd.read_excel(fn, header = None)
df2 = pd.DataFrame(x)
writer = pd.ExcelWriter(fn)
df2.to_excel(writer, startcol=0, startrow=1, header=None, index=False)
writer.save()

What this gets me is the correct information but seemingly overwrites any existing data.这给我的是正确的信息,但似乎覆盖了任何现有数据。 All other cell contents and sheets are now gone and the newly added data is in an otherwise blank Sheet1.所有其他单元格内容和工作表现在都消失了,新添加的数据在一个空白的 Sheet1 中。 I need to maintain the existing spreadsheet as-is, and only add this info starting at a given cell on a given sheet.我需要按原样维护现有的电子表格,并且仅从给定工作表上的给定单元格开始添加此信息。

Have also tried the following with xlwings, which imports the correct data into the existing sheet while maintaining all other data, but replaces the first cell with a 0. How do I get rid of this extra 0 from the dataframe?还使用 xlwings 尝试了以下操作,它在保留所有其他数据的同时将正确的数据导入现有工作表,但将第一个单元格替换为 0。如何从数据框中删除这个额外的 0?

filename = "C:\\Users\\user\\Documents\\test.xlsx"
df = pd.DataFrame(x)
wb = xw.Book(filename)
ws = wb.sheets('Sheet1')
ws.range('A2').options(index=False).value = df
wb = xw.Book(filename)

EDIT: The above xlwings code appears to work if I replace DataFrame with Series.编辑:如果我用 Series 替换 DataFrame,上面的 xlwings 代码似乎可以工作。 SOLUTION:解决方案:

import xlwings as xw
filename = "C:\\Users\\user\\Documents\\test.xlsx"
df = pd.Series(x)
wb = xw.Book(filename)
ws = wb.sheets('Sheet1')
ws.range('A2').options(index=False).value = df
wb = xw.Book(filename)

I need to maintain the existing spreadsheet as-is我需要按原样维护现有的电子表格

Open the excel file in append mode, take a look at this answer for example (other answers in the same thread are useful as well).以追加模式打开 excel 文件,例如查看此答案(同一线程中的其他答案也很有用)。

If you want to reference excel sheet by its indexing eg("A1") you can use openpyxl如果您想通过索引引用 Excel 表,例如(“A1”),您可以使用openpyxl

from openpyxl import load_workbook

workbook = load_workbook(filename="sample.xlsx")
ll = ["apple", "orange", "grape"]
sheet = workbook.active

sheet["A2"] = ll[0]
sheet["A3"] = ll[1] 
sheet["A4"] = ll[2]

workbook.save(filename="sample.xlsx")

Guess this solves your problem猜猜这解决了你的问题

Depending on how your data is formatted, this may work, if you are satisfied appending to the next empty column in the sheet.如果您对附加到工作表中的下一个空列感到满意,这可能会起作用,具体取决于您的数据的格式。 With this proviso, the pandas library is really good for handling tabular data and can work with Excel files (using the openpyxl library).有了这个条件, pandas库非常适合处理表格数据,并且可以处理 Excel 文件(使用openpyxl库)。

It looks like you've installed pandas already but, for the benefit of others reading, make sure you've installed pandas and openpyxl first:看起来您已经安装了 Pandas,但为了其他人阅读的利益,请确保您首先安装了 Pandas 和 openpyxl:

pip install pandas openpyxl

Then try:然后尝试:

import pandas as pd
df = pd.read_excel('filename.xlsx')
df['new_column_name'] = listname
df.to_excel('output_spreadsheet.xlsx')

I personally find that more readable than using openpyxl directly.我个人认为这比直接使用 openpyxl 更具可读性。

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

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