my app has to deal with a lot of dbf which sometimes get
corrupted.  upon checking, the corruption is most likely due to
some additional bytes after the logical end of the file.  the
problem is vfp9 refuses to open it with error 2091:

table "name" has become corrupted. the table will need to be repaired before using again.

it always puzzle me why vfp does not any built-in dbf repair command
(not even the simple one) although it has a native dbf engine.

lately the frequency of corruption get to a point becomes
annoying.  so i look around the net to see if there is any dbf
repair utility which i can incorporate into my app to fix the
corruption automatically when it is detected.

there are some but it is not apparent that they support command line
execution or ole automation, and they are not cheap.  my client
probably doesn't like absorbing the cost of it.

but my client has excel installed in every workstation, and i noticed
that excel can open the corrupted dbf okay without any problem. 
so i wrote a routine to use excel to repair the dbf.  it simple
asks excel to open the corrupted dbf and save it again.  it
probably will not repair all kinds of corruption, but at least it works
in my case.  please see if it works for you as a dbf repair
alternative.

*------------------------------------------------------------------------
* ut_repairdbf()
*
* call this routine to repair a dbf file reported by vfp to be corrupted.
*
* passes:
*   tcfile = the full path to the dbf file to be repaired.
*            e.g. 'c:\path\table.dbf'
*
* returns:
*   .t. if successful, .f. otherwise.
*
* output:
*   the original dbf is backup with .bak extension.
*   the repaired dbf has the same name as the original file.
*  
* example:
*   ut_repairdbf('c:\path\table.dbf')
*
* remarks:
*   microsoft excel is used to repair the dbf.
*------------------------------------------------------------------------
function ut_repairdbf(tcfile)

   local loexcel as excel.application
   local lcbackupfile
   local lcfixedfile
  
   if empty(tcfile) or not file(tcfile)
      return .f.
   endif
  
   loexcel = createobject("excel.application")
   if vartype(loexcel)<>'o'
      return .f.
   endif
  
   lcbackupfile = alltrim(tcfile)+'.bak'
   lcfixedfile = alltrim(tcfile)+'.tmp'

   delete file (lcbackupfile)
   delete file (lcfixedfile)
  
   loexcel.workbooks.open(tcfile)
   loexcel.activeworkbook.saveas(lcfixedfile, xldbf3)
   loexcel.activewindow.close(.f.)
   loexcel.quit()
  
   rename (tcfile) to (lcbackupfile)
   rename (lcfixedfile) to (tcfile)
endfunc
 

6 Responses to Use Excel to repair DBF

Leave a Reply

Your email address will not be published. Required fields are marked *