Skip to main content
 首页 » 编程设计

python之使用 Python 将数据从 MS Access 复制到 MS Excel

2025年05月04日20Renyi-Fan

周末的大部分时间我都在尝试找出使用 Python 将数据从 MS Access 表传输到 Excel 工作表的最佳方法。我发现了一些可能有帮助的模块(execsql、python-excel),但由于我的知识有限,而且我必须使用这些模块来创建某些数据(我是一名 GIS 专业人员,所以我正在使用创建空间数据ArcGIS arcpy 模块到 Access 表)

我不确定最好的方法应该是什么。我需要做的就是从access中复制4列数据到excel,然后格式化excel。我已经解决了格式化部分。

我应该:

使用游标遍历行并以某种方式将行加载到 excel 中? 将列从 access 复制到 excel? 将整个 Access 表导出到 excel 中的工作表中?

感谢您的任何建议。

请您参考如下方法:

我最终找到了一种方法来做到这一点。我想我会为可能遇到相同情况的任何人发布我的代码。我使用了一些 GIS 文件,但如果你不这样做,你可以将变量设置为目录路径而不是使用 env.workspace 并使用游标搜索而不是 arcpy.SearchCursor 函数,那么这是可行的。

import arcpy, xlwt 
from arcpy import env 
from xlwt import Workbook 
 
# Set the workspace. Location of feature class or dbf file. I used a dbf file. 
env.workspace = "C:\data" 
 
# Use row object to get and set field values 
cur = arcpy.SearchCursor("SMU_Areas.dbf") 
 
# Set up workbook and sheet 
book = Workbook() 
sheet1 = book.add_sheet('Sheet 1') 
book.add_sheet('Sheet 2') 
 
# Set counter 
rowx = 0 
 
# Loop through rows in dbf file. 
for row in cur: 
    rowx += 1 
    # Write each row to the sheet from the workbook. Set column index in sheet for each column in .dbf 
    sheet1.write(rowx,0,row.ID) 
    sheet1.write(rowx,1,row.SHAPE_Area/10000) 
    book.save('C:\data\MyExcel.xls') 
 
del cur, row