[Problem Solved] When xlwings handles excel copy and paste, the number automatically becomes scientific notation

Problem: After copying the data from one excel to another, it is found that the numbers are automatically changed to scientific notation, the code is as follows

import xlwings as xw
app = xw.App(visible=False,add_book=False)
# 打开两个excel文件
book1 = app.books.open("test1.xlsx")
book2 = app.books.open("test2.xlsx")
# 复制到另一个excel
book1.sheets[0]['A2:AA15'].value = book2.sheets[0]['A2:AA15'].value
# 保存文件
book1.save()
book1.close()
app.kill()

Solution: The corresponding cell format in test1.xlsx is conventional , so the data copied in the past automatically becomes scientific notation, so it is enough to set the cell format to text. The modified code is as follows

import xlwings as xw
app = xw.App(visible=False,add_book=False)
# 打开两个excel文件
book1 = app.books.open("test1.xlsx")
book2 = app.books.open("test2.xlsx")
# 将这些单元格都设置为文本格式
book1.sheets[0]['A2:AA15'].api.NumberFormat = "@"
# 复制到另一个excel
book1.sheets[0]['A2:AA15'].value = book2.sheets[0]['A2:AA15'].value
# 保存文件
book1.save()
book1.close()
app.kill()

Guess you like

Origin blog.csdn.net/qq_33218097/article/details/129707577