Giuseppe Lolli
Giuseppe Lolli

Reputation: 177

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

For a project i was to trying to do this:

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!

Upvotes: 1

Views: 3815

Answers (2)

StefTheo
StefTheo

Reputation: 449

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.

Upvotes: 0

Andrea
Andrea

Reputation: 12405

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'
)

Upvotes: 3

Related Questions