使用Python将文本插入Excel会创建Bubbles

时间:2014-06-27 07:32:02

标签: python excel copy-paste

使用Python将文本输入到Excel文件中,我在Excel 2010中遇到了一些问题。但它可以使用Excel 2013.我已经在2台不同的PC上进行了测试。在Excel 2010上的一个PC上,Excel崩溃,另一方面,它进入这些类型的气泡(它们的行为就像图像 - 你甚至可以调整它们的大小):

enter image description here

代码的工作方式如下:我创建一个字符串,按 \r\n指示行更改,并使用Excel.DispatchPasteSpecial粘贴。

不正确插入的原因是什么?

def pasteToExcel(excelfile, sheet, data, startcell):
    if type(data) == list:
        rows = 1
        cols = len(data)
    elif type(data) == pd.DataFrame:
        rows = data.shape[0]
        cols = data.shape[1]
    elif type(data) == int or float:
        rows = 1
        cols = 1
    elif type(data) == str:
        rows = 1
        cols = 1

    cellrange = startcell
    text = ""

    cellrange = calculateCellRange(startcell,rowcount=rows,colcount=cols)

    if type(data) == pd.DataFrame:
        print "  Erkannter Datentyp vom Input: pd.DataFrame"
        line_strings = []
        for row in range(rows):
            for col in range(cols-1): 
                line_strings.append(str(data.ix[row,col])+"\t") #cell change: \t
            line_strings.append(str(data.ix[row,data.shape[1]-1])+"\r\n")

        for item in line_strings:
            item = item.replace(".",",")
            text += item

    elif type(data) == str:
        text = data

    elif type(data) == list:
        line_strings = []
        for index in range(len(data)): # 0 1 2           len(data) =3 ; range(2) = 0,1
            if index < len(data)-1:
                line_strings.append(str(data[index])+"\t") #cell change: \t
            elif index == len(data)-1:
                line_strings.append(str(data[index])+"\r\n")

        for item in line_strings:
            item = item.replace(".",",")
            text += item

    clipboard.OpenClipboard()
    clipboard.EmptyClipboard()
    clipboard.SetClipboardText(text)
    clipboard.CloseClipboard()

    excel = Dispatch("Excel.Application")
    excel.Visible = 0
    wb = excel.Workbooks.Open(excelfile) 
    ws = wb.Worksheets(sheet)
    ws.Activate()
    ws.Range(cellrange).Select()
    wb.ActiveSheet.PasteSpecial()
    excel.DisplayAlerts = False
    excel.ActiveWorkbook.Save()
    excel.Quit()

0 个答案:

没有答案