Using Python to enter text into an Excel file, I have a little problem that occurs with Excel 2010. It is however working with Excel 2013. I've tested on 2 different PC's. On one Pc with Excel 2010, Excel crashes, on the other, it enters these kind of bubbles (they behave like images - you can even resize them):
The code works like this: I create a string, indicating line changes by
\r\n
, and pasting with Excel.Dispatch
and PasteSpecial
.
What can be the reason for not inserting correctly?
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()