dbf转xls - 第一非表头行未写入

1 投票
1 回答
503 浏览
提问于 2025-04-17 17:52

我想用Python把.dbf文件转换成.xls文件。我参考了这个代码片段,但是我用这个代码时,第一行非标题行没有写出来:

    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")

我该怎么才能把第一行非标题行写出来呢?

谢谢

1 个回答

2

你在处理dbf文件时,第一行(也就是第0行)被忽略了。在dbf文件中,列名并不是一行数据。而在Excel文件中,第一行是表头,所以在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。

撰写回答