Question

I would like to convert .dbf file to .xls using python. I've referenced this snippet, however I cannot get the first non header row to write using this code:

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

How can I get the first non header row to write?

Thanks

Was it helpful?

Solution

You are missing out row 0 in the dbf which is the first row. In dbf files the column names are not a row. However row 0 in the Excel file is the header so the index needs to differ in the dbf and the xls so you need to add 1 to the row used in the Excel worksheet.

So

for row in range(len(dbf)):
    for col in range(len(dbf.fieldNames)):
        sheet1.row(row+1).write(col, dbf[row][col])

Note the snipper referred to does not add the 1 in the range either

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top