Home > Back-end >  How to apply Excel Table Style using Powershell
How to apply Excel Table Style using Powershell

Time:12-02

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


CodePudding user response:

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 and tutorials over the internet if you want to learn more.

  • Related