使用powershell将accdb转换为csv

时间:2011-04-19 00:42:40

标签: powershell csv ms-access

我正在尝试将一些excel(.xlsx)和Access(.accdb)转换为CSV文件。

我很快找到了使用Excel执行此操作的方法,但现在我找不到有关转换.accdb文件的任何有用文档。

到目前为止,我有:

        $adOpenStatic = 3
        $adLockOptimistic = 3

        $objConnection = New-Object -com "ADODB.Connection"
        $objRecordSet = New-Object -com "ADODB.Recordset"


        $objConnection.Open("Provider = Microsoft.ACE.OLEDB.12.0; Data Source = " + $Filepath)
        $objRecordset.Open("Select * From TableName",$objConnection,$adOpenStatic, $adLockOptimistic)

#Here I need some way to either saveas .csv or loop through
#each row and pass to csv.

        $objRecordSet.Close()
        $objConnection.Close()

任何想法?

如果有人知道某种方式,我愿意用另一种语言(VB,Java,PHP)来做这件事。

2 个答案:

答案 0 :(得分:3)

如果使用.NET而不是COM,则更容易。这是一些处理Excel XLSX文件的代码

#Even /w Excel 2010 installed, needed to install ACE:
#http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c06b8369-60dd-4b64-a44b-84b371ede16d&displaylang=en
#Becareful about executing in "right" version x86 vs. x64
#Change these settings as needed
$filepath = 'C:\Users\u00\Documents\backupset.xlsx'
#Comment/Uncomment connection string based on version
#Connection String for Excel 2007:
$connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=`"$filepath`";Extended Properties=`"Excel 12.0 Xml;HDR=YES`";"
#Connection String for Excel 2003:
#$connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=`"$filepath`";Extended Properties=`"Excel 8.0;HDR=Yes;IMEX=1`";"
$qry = 'select * from [backupset$]'


$conn = new-object System.Data.OleDb.OleDbConnection($connString)
$conn.open()
$cmd = new-object System.Data.OleDb.OleDbCommand($qry,$conn) 
$da = new-object System.Data.OleDb.OleDbDataAdapter($cmd) 
$dt = new-object System.Data.dataTable 
[void]$da.fill($dt)
$conn.close()
$dt | export-csv ./test.csv -NoTypeInformation

答案 1 :(得分:1)

如果你想坚持使用ADODB COM对象:

# loop through all records - do work on each record to convert it to CSV
$objRecordset.Open("Select * FROM Tablename", $objConnection,$adOpenStatic,$adLockOptimistic)

$objRecordset.MoveFirst()

do {
# do your work to get each field and convert this item to CSV
# fields available thru: $objRecordset.Fields['fieldname'].Value
$objRecordset.MoveNext()

} while ($objRecordset.EOF -eq $false)

$objRecordset.Close()