我正在努力使用 xlrd/xlwt/xlutils 编辑现有的 xls 工作簿我可以更改 xlrd 工作簿中的值,但我需要将它们写入现有工作簿中。我的代码不起作用,我知道 alghorytm 是正确的,但代码不是。
rb = open_workbook(filename)
#set active sheet
rs = rb.sheet_by_index(0)
#make instance for xlsutils
wb = copy(rb)
ws = wb.get_sheet(0)
rows = rs.nrows
cols = rs.ncols
#iterate and prepare format for SQL db tables
for row_idx in range (0,rows):
for col_idx in range (0,cols):
cell=rs.cell(row_idx,col_idx)
clval = cell.value
cltp = cell.ctype
if cltp == xlrd.XL_CELL_BLANK:
clval ="xy"
ws.write(row_idx,col_idx,"xy")
elif cltp == xlrd.XLDateError:
date_format = XFStyle()
date_format.num_format_str = 'dd/MM/yyyy'
clval = '01/01/2018'
ws.write(row_idx,col_idx, '01/01/2018', date_format)
elif cltp == xlrd.XL_CELL_EMPTY:
clval="XYU"
ws.write(row_idx,col_idx,"xy")
elif cltp == xlrd.XL_CELL_NUMBER:
if clval < 0:
clval=0
ws.write(row_idx, col_idx,0)
elif cltp == xlrd.XL_CELL_TEXT:
clval = ftfy.fix_text(clval)
ws.write(row_idx,col_idx, ftfy.fix_text(clval))
elif clval == -693594:
date_format = XFStyle()
date_format.num_format_str = 'dd/MM/yyyy'
clval='01/01/2018'
ws.write(row_idx, col_idx,'01/01/2018',date_format)
#print (row_idx,col_idx)
print(clval)
save(wb,'abbcards_2.xls')
Output:
File "D:/rs_al/IdeaProjects/ExcelToSQL/PyXLSSQL/XLStoSQL.py", line 69, in
xls_wrk
save(wb,'abbcards_2.xls')
File "C:\Python\lib\site-packages\xlutils\save.py", line 24, in save
StreamWriter(stream)
File "C:\Python\lib\site-packages\xlutils\filter.py", line 941, in process
reader(chain[0])
File "C:\Python\lib\site-packages\xlutils\filter.py", line 65, in __call__
filter.workbook(workbook,filename)
File "C:\Python\lib\site-packages\xlutils\filter.py", line 291, in workbook
self.wtbook.dates_1904 = rdbook.datemode
AttributeError: 'Workbook' object has no attribute 'datemode'
我想我打印存在于 xlrd 工作簿的内存实例中,值是正确的。但是怎么写呢?
我不明白 xlutils 的副本到底做了什么。它会制造另一个物体吗?如果是这样,如何使用 xlrd+xlwt 进行写作?我发现不能使用 pandas,因为我需要确切地知道单元格类型,才能更改那里的值。
在java中,我用一个包做了同样的事情,其中有方法在同一个对象中读取/写入/保存。