简体   繁体   中英

How to save an Excel (xlsm) as CSV file with semicolon delimiter?

For a project i was to trying to do this:

  • Using powershell, open an excel file. (Done)
  • Refresh the table with a data connection to a website. (Done)
  • Save refreshed Excel in the same path.(Done)
  • Convert that file into a CSV used to be loaded into SQL Server (epic fail)

Powershell save the file with the comma separator, not with the semicolon:

#Refresh Excel
$app = New-Object -comobject Excel.Application
$app.Visible = $false
$wb = $app.Workbooks.Open("C:\test\test.xlsm")
$wb.Name
$wb.RefreshAll()
$wb.Save()
$wb.Close()
$app.Quit()

#Export To CSV
Function ExportWSToCSV ($excelFileName, $csvLoc)
{
    $excelFile = "C:\test\" + $excelFileName + ".xlsm"
    $E = New-Object -ComObject Excel.Application
    $E.Visible = $false
    $E.DisplayAlerts = $false
    $wb = $E.Workbooks.Open($excelFile)
    foreach ($ws in $wb.Worksheets)
    {
        $n = $excelFileName + "_" + $ws.Name
        write-host $n
        write-host ($csvLoc + $n + ".csv")
        $ws.SaveAs($csvLoc + $n + ".csv",6)
    }
    $E.Quit()
}

ExportWSToCSV -excelFileName "test" -csvLoc "C:\test\new\"

I need also how to bulk insert data into a table in SQL Server...

Thanks in advance!

To save a CSV using semicolon as separator instead of comma try specifying a $true value for local parameter for the SaveAs metohd:

$ws.SaveAs($csvLoc + $n + ".csv",6, 0, 0, 0, 0, 0, 0, 0, $true)

instead of:

$ws.SaveAs($csvLoc + $n + ".csv",6)

This is an excerpt from MSDN explaining the local parameter (more info here ):

Local

Type: System.Object

true saves files against the language of Excel (including control panel settings); false ( default ) saves files against the language of Visual Basic for Applications (VBA).

To bulk insert you CSV files into SQL Server (in this example my CSV file has only 2 columns):

IF  OBJECT_ID('dbo.IMPORT_FROM_CSV') IS NOT NULL
DROP TABLE dbo.IMPORT_FROM_CSV 

CREATE TABLE dbo.IMPORT_FROM_CSV (
  [COL_1]            [VARCHAR] (max) NULL,
  [COL_2]            [VARCHAR] (max) NULL
)

BULK INSERT dbo.IMPORT_FROM_CSV
FROM 'C:\test\new\test_Sheet1.csv'
WITH (
 FIRSTROW = 2,
 FIELDTERMINATOR = ';',
 ROWTERMINATOR = '\n'
)

When I am running into seperators problems I just add two lines to my code in general

(Get-Content -Path "C:\test\new\test.csv") | % {$_ -replace ';' , '|'}|
Out-File -FilePath "C:\test\new\test.csv" -Encoding UTF8

you can adjust your seperators and replace them, I use the '|' one because it is difficult to find as part of a text.

Hope this helps you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM