Python - 添加字符串到剪贴板,并以正确的格式粘贴到Excel中 (即,按行列分开)

问题描述 投票:0回答:1

我看到了一些关于这个问题的答案,但是在VBA和C#中----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------在python 3中,我试图做以下事情。

  1. 用excel格式给一个变量赋值字符串
  2. 将这个变量复制到剪贴板上。
  3. 然后,用户应该能够手动CTRL+V(粘贴)这个字符串到excel中,并让它分离到正确的rowcolumn位置。

我在项目中同时使用了tkinter和openpyxl,通过测试我得到了一些结果,但这不是我想要的。 我得到的最接近的结果如下。

# If I first go into excel, 
# and copy a few columns within a single row with different data in them, 
# then I run the following code: 

import tkinter as tk
root = tk.Tk()
paste = root.clipboard_get()

print(paste)

# Then I manually copy the print output to the clipboard,
# and then go back to excel and paste, 
# excel gives the following warning message:
# "The data you're pasting isn't the same size as your selection.  do you want to paste anyways?"
# And after pressing OK, it seems as though the data is pasted properly. 

这是确定的,print(paste)字符串可能会帮助我为我要生成的字符串初始变量创建适当的格式,但我需要一个不会导致Excel每次都弹出这个警告标志的解决方案。

如果有人能对此提供一些见解,我将非常感激。 另外,解决方案需要通过python而不是通过修改Excel来实现。 其次,解决的方法不是直接将数据追加写入Excel(通过Openpyxl等),而是将数据以适当的格式传到剪贴板(我用的是Excel 2016)。

谢谢!!!。


编辑。

我也尝试过使用 "ctypes解决方案 "提出的方法。此处 由用户kichik提供。

为了让这个解决方案更容易操作,我下载了一个名为 "InsideClipboard "的应用程序,它可以让我轻松地看到剪贴板 "复制 "数据的每一种类型的格式ID。

利用kichik的ctype解决方案,我检查了一下,手动复制剪贴板中存储的不同格式的打印输出,是否可以让我手动CTRL+V到Excel的原始格式,但失败了。 原来 "复制 "的是Excel中的多列字符串,而将各个格式手动 "粘贴 "回excel中后,所有的字符串都保留在一个单元格中(HTML格式除外,它创建了多行数据--也是错误的)。 不同的格式包括CF_LOCALE (16), CF_TEXT (1), CF_OEMTEXT (7), CF_UNICODETEXT (13), 和HTML Format (49384)。

所以,还是:无解。


编辑2:

我意识到我可以在python中创建字符串,并在字符串之间按下实际的制表符,而不是使用\t,它的工作是创建一个单一的字符串,当粘贴到Excel中时,它将把数据放入单行的不同列中。

另外,我意识到,如果我直接在Excel中按CTRL+V键(而不是在行标题上),在我想粘贴数据的实际行中,我不再得到Excel的 "警告信息"。 所以,使用这个变通方法可能会有用。 如果没有人有什么意见,那么这个简单的方法可能就足够了。

但是,我希望能够简单地点击行标题而不是第一个相关行单元格来粘贴数据,而不出现Excel的警告弹窗。仍然欢迎大家提出想法,最好是通过python来完成(不需要修改Excel,因为该应用可能会在不同的Windows操作系统PC上运行)。

所以:可能的简单解决方案,但不完美。


编辑3:

所以,我在编辑2的基础上想出了一个解决方案。 如果Excel在工作电脑上以应用程序的形式打开,那么Excel的 "警告 "弹窗仍然会发生;但是,如果Excel文件是通过在线处理器打开并可编辑的,那么用户可以高亮显示行标题并粘贴,而不会产生Excel的 "警告 "弹窗。 这在我的具体情况下是可行的,不过更好的解决方案是让复制的数据在任何情况下都不产生Excel "警告 "弹窗。 不管怎样,如果没有人知道如何单独通过python来防止Excel警告弹出,那么我还是可以用这个方法来工作。

这是我的解决方案(注意,长字符串中的空格其实是 "tab")。

import pyperclip

# t variables are defined prior to the below code
# note: the "   " parts in the data string are actually tabs

data = t1 + "   " + t2 + "  " + "   " + t3 + "  " + t4 + "  " + t5 + "  " + t6 + "  " + t7 + "  "  + "  " + "t8"  + "   "  + "  "  + "  "  + "  "  + "  "  + "  " + t9 + "  " + t10 + " " + t11 + " " + t12 + " "  + "  "  + "  "  + "  "  + "  "  + "  " + t13

pyperclip.copy(data)
print("clipboard:", data)

# now manually pressing CTRL+V while inside Excel (online processor) will
# paste the various t variables in the appropriate cells designated by 
# the "   " tabs in between.  Of note, this works for columns of a single
# row as I didn't need multiple rows of data for my task.
excel python-3.x tkinter clipboard openpyxl
1个回答
0
投票

下面是在tkinter中创建一个5行3列的Entries网格的代码。 按 "复制 "按钮将 "条目 "的内容复制为一个标签换行分隔的字符串到剪贴板,然后可以粘贴到excel中。

import tkinter as tk
from tkinter import ttk

ROWS = 5
COLS = 3

root = tk.Tk()

rows = []  # Container for Entry widgets.

# Create and grid the Entry widgets.
for row in range( ROWS ):
    temp = []
    for col in range( COLS ):
        temp.append( ttk.Entry(root, width = 10 ))
        temp[-1].grid( row = row, column = col )
    rows.append( temp )

def entries_to_lists( rows ):
    list_out = []
    for row in rows:
        temp = []
        for col in row:
            temp.append( col.get() )
        list_out.append( temp )
    return list_out

def string_out( rows ):
    """ Prepares a '\t', '\n' separated string to send to the clipboard. """
    out = []
    for row in rows:
        out.append( '\t'.join( row ))  # Use '\t' (tab) as column seperator.
    return '\n'.join(out)              # Use '\n' (newline) as row seperator.

def do_copy():
    data = entries_to_lists( rows )
    root.clipboard_clear()
    root.clipboard_append( string_out( data ))     # Paste string to the clipboard
    root.update()   # The string stays on the clipboard after the window is closed

ttk.Button( text = "  Copy  ", command= do_copy ).grid( column = 1 )
# Button to trigger the copy action.

root.title("Copy to Excel Test")
root.geometry("400x200+10+10")
root.mainloop()

这在Windows 10中复制到Excel 2013中没有任何警告信息。

string_out 将从任何一个字符串列表中生成一个合适的字符串,一个二维列表。

© www.soinside.com 2019 - 2024. All rights reserved.