Python – Saving *.dbf as *.xls Using ArcGIS Desktop

arcgis-10.0arcgis-desktopdbfexcelpython

I've been let loose in the workplace to learn python to do things in Arcmap 10.
so, I am learning python as I go and trying to remember the programming I have done.

Where I am in this project is converting a dbf, or csv, xls in a simple fashion.
from there, all the files will be copied together into one file.
I've got the all-in-one xls working, but I can't find an easy, simple dbf to xls solution.

I condensed code found here:
http://blog.gmane.org/gmane.comp.python.education/page=12

into:

from xlwt import Workbook
import dbfpy.dbf

input0 = '...file.dbf'
output = '...file.xls'

def test1():
    dbf = dbfpy.dbf.Dbf(input0)
    book = Workbook()
    sheet1 = book.add_sheet('Sheet 1')
    for row in range(len(dbf)):
        for col in range(2):#chop to two for my purposes, gm 
            sheet1.row(row).write(col, dbf[row][col])
    book.save(output)

test1()

This works, minus the lack of field names.

Best Answer

Like whuber says, you have to write out the headers explicitly. I loaded up dbfpy and xlwt in a virtualenv and ran this:

from xlwt import Workbook, easyxf
import dbfpy.dbf
from time import time

def test1():
    dbf = dbfpy.dbf.Dbf("pipelines.dbf", readOnly = True)

    header_style = easyxf('font: name Arial, bold True, height 200;')

    book = Workbook()
    sheet1 = book.add_sheet('Sheet 1')

    for (i, name) in enumerate(dbf.fieldNames):
        sheet1.write(0, i, name, header_style)

    for (i, thecol) in enumerate(dbf.fieldDefs):
        name, thetype, thelen, thedec = str(thecol).split()
        colwidth = max(len(name), int(thelen))
        sheet1.col(i).width = colwidth * 310

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

    book.save("pipelines-xls.xls")

if __name__ == "__main__":
    start = time()
    test1()
    end = time()
    print end - start

This gives me headers in my xls:

enter image description here

Related Question