Convert CSV to XLSX via PowerShell

Revisiting an old friend as some date format junk was needing adjustment and leading 0s from txt file were being dropped. Script originally brought txt into xlsx and all data was “General” format. Tweak noted below brought all data into xlsx as “Text” format.

Changed:

$query.TextFileColumnDataTypes = ,1 * $worksheet.Cells.Columns.Count
to
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count

Entire script with stuff removed to protect the martians:

# Define locations and delimiter
$SourceFolder = "\\server\share\path1\path2"
$csv = $SourceFolder+"\sourcefile.txt" #Location of the source file
$xlsx = $SourceFolder+"\Cool Filename "+(Get-Date -f dd)+"."+(Get-Date -f MM)+"."+(Get-Date -f yyyy)+".xlsx" #Desired location of output
$delimiter = "|" #Specify the delimiter used in the file

# REMOVE ALL .XLSX files in the folder
Remove-Item $SourceFolder\* -include *.xlsx

# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()

# Legacy file process rename tasks
dir \\server\share\path1\file.txt | Rename-Item -NewName {"New_Filename_"+(Get-Date -f yyyyMMdd)+".csv"}
dir \\server\share\path1\file2.txt | Rename-Item -NewName {"Another_File_"+(Get-Date -f yyyyMMdd)+".csv"}

Source: https://code.adonline.id.au/csv-to-xlsx-powershell/

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.