我想使用 python 将 .dbf 文件转换为 .xls。我引用了这个snippet ,但是我无法使用此代码编写第一个非标题行:
from xlwt import Workbook, easyxf
import dbfpy.dbf
dbf = dbfpy.dbf.Dbf("C:\\Temp\\Owner.dbf")
book = Workbook()
sheet1 = book.add_sheet('Sheet 1')
header_style = easyxf('font: name Arial, bold True, height 200;')
for (i, name) in enumerate(dbf.fieldNames):
sheet1.write(0, i, name, header_style)
for row in range(1, len(dbf)):
for col in range(len(dbf.fieldNames)):
sheet1.row(row).write(col, dbf[row][col])
book.save("C:\\Temp\\Owner.xls")
如何获取要写入的第一个非标题行?
谢谢
最佳答案
您遗漏了 dbf 中的第一行即第 0 行。在 dbf 文件中,列名不是一行。然而,Excel 文件中的第 0 行是标题,因此 dbf 和 xls 中的索引需要不同,因此您需要向 Excel 工作表中使用的行添加 1。
所以
for row in range(len(dbf)):
for col in range(len(dbf.fieldNames)):
sheet1.row(row+1).write(col, dbf[row][col])
请注意,引用的片段也不会在范围内添加 1
关于python - dbf 到 xls - 第一个非标题行未写入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15203423/