1

I'm thinking about writing script that convert my existing CSV file to XLSX file so I been following this post https://code.adonline.id.au/csv-to-xlsx-powershell/

and it's working fine but I'm just wondering how can I format as a table and apply style while converting to XLSX file?

I'll be really appreciated if I can get any help or suggestion.

### Set input and output path
$inputCSV =  "C:\AuditLogSearch\Modified Audit-Log-Records.csv"
$outputXLSX = "C:\AuditLogSearch\output1.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
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

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

$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()


1
  • @SantiagoSquarzon Hi again, can you please provide me an example that have import csv and export it to xlsx file with formated table style. Commented Dec 1, 2021 at 22:43

1 Answer 1

3

Assuming you want to try out the ImportExcel Module.

  • Install it first: Install-Module ImportExcel -Scope CurrentUser

Then the code would look like this:

$params = @{
    AutoSize      = $true
    TableName     = 'exampleTable'
    TableStyle    = 'Medium11' # => Here you can chosse the Style you like the most
    BoldTopRow    = $true
    WorksheetName = 'YourWorkSheetName'
    PassThru      = $true
    Path          = 'path/to/excel.xlsx' # => Define where to save it here!
}

$xlsx = Import-Csv path/to/csv.csv | Export-Excel @params
$ws   = $xlsx.Workbook.Worksheets[$params.Worksheetname]
$ws.View.ShowGridLines = $false # => This will hide the GridLines on your file
Close-ExcelPackage $xlsx

The author has a Youtube channel where he used to upload tutorials and there is also online Documentation over the internet if you want to learn more.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.