开发者

Converting accdb to csv with powershell

I am trying to convert some excel (.xlsx) and Access (.accdb) to CSV files.

I quickly found a way to do this with Excel but now I cannot find any helpful documentation on converting .accdb files.

So far I have:

        $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 开发者_JAVA百科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()

Any Ideas?

I would be willing to do this with another language (VB, Java, PHP) if anyone knows a way.


If you use .NET rather than COM it's a lot easier. Here's some code to handle the Excel XLSX files

#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


If you want to stick with ADODB COM object:

# 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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜