Powershell convert csv to xlsx - excel

I have the below Powershell script to convert excell csv file to xlsx which work fine. I am running into a problem, when the csv file have german letters like "Ä,ü,ß", these are being replaced in xlsx file with
ü or something like this. I would like to save the file using UTF-8 when saving to xlsx
How can I save xlsx with desired encoding?
### Set input and output path
$inputCSV = "test.csv"
$outputXLSX = "output.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(3)
### 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()
### Save & close the Workbook as XLSX. Change the output extension for Excel 2003 overwrite
$excel.DisplayAlerts = $False
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()

string csvFileName = #"test.csv";
string excelFileName = #"output.xlsx";
string worksheetsName = "TEST";
bool firstRowIsHeader = false;
var format = new ExcelTextFormat();
format.Delimiter = ',';
format.EOL = "\r";
//format.TextQualifier = '"';
format.Encoding = new UTF8Encoding();
format.DataTypes = new eDataTypes[] { eDataTypes.Number, eDataTypes.String };
ExcelPackage.LicenseContext = LicenseContext.Commercial;
using (ExcelPackage package = new ExcelPackage(new
FileInfo(excelFileName)))
{
ExcelWorksheet worksheet =
package.Workbook.Worksheets.Add(worksheetsName);
worksheet.Cells["A1"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
package.Save();
}

Related

How to apply Excel Table Style using Powershell

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

How to create a new sheet in excel with powershell script

My question is in the title, i dont know how to create a new sheet in excel using a powershell script.
here is my code :
#Define locations and delimiter
$csv = $pathcsv
$xlsx = $pathxlsx
$delimiter = "," #Specify the delimiter used in the file
# 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 = ,1 * $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)
$Workbook = $excel.Workbooks.Open($pathxlsx)
Add-Worksheet -ExcelPackage $excel -WorkSheetname "test"
$excel.Quit()
pause
So i try the commande Add-Worksheet -ExcelPackage $excel -WorkSheetname "test" but it seems not working, can you help me with that ?
I got the following error :
Add-Worksheet : Unable to process argument transformation on parameter "ExcelPackage". impossible to
convert the value "Microsoft.Office.Interop.Excel.ApplicationClass" to type "
Microsoft.Office.Interop.Excel.ApplicationClass "and type" OfficeOpenXml.ExcelPackage ".
Au caractère C:....\NEW.ps1:125 : 29
Add-Worksheet -ExcelPackage $excel -WorkSheetname "NewSheet"
~~~~~~
CategoryInfo : InvalidData : (:) [Add-Worksheet], ParameterBindingArgumentTransformationException
FullyQualifiedErrorId : ParameterArgumentTransformationError,Add-Worksheet
thanks
To append a new sheet to the opened Excel file as last sheet, you can do the following:
Remove the line Add-Worksheet -ExcelPackage $excel -WorkSheetname "test" and instead write:
# get the last sheet in the workbook
$lastSheet = $Workbook.WorkSheets($Workbook.WorkSheets.Count)
# create a new sheet and insert it before the last sheet
$newSheet = $workbook.WorkSheets.Add($lastSheet)
# give it a name
$newSheet.Name = 'test'
# now move the previous last sheet before the new sheet, so now THAT will become the last
$lastSheet.Move($newSheet)
# Save & close the Workbook as XLSX.
$workbook.SaveAs("D:\Test\test.xlsx",51)
$excel.Quit()
# don't forget to clear the COM objects from memory
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($lastSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($newSheet)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

How to format CSV file into XLSX with correct spacing?

So I have a PowerShell Script that takes a CSV file with data inputted from sensors, and converts it into an Excel sheet and then prints it. My problem is that I can not get the format of the Excel sheet to be able to have the width of all my columns fit onto one page. I can have as many portrait pages as I want, but I need all columns to fit on one page.
I have tried: Ranges, Making things bold or not, and using the auto resize feature. None have worked.
$delimiter = ","
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$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 = ,1 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
# Execute & delete the import query
$query.Refresh()
$query.Delete()
#Green blocks if number passes
for($i=6;$i -le 84;$i++){
if($worksheet.Cells.Item($i,6).value2 -match "True"){
$Worksheet.Cells($i,4).Interior.ColorIndex = 4
}
if($worksheet.Cells.Item($i,6).value2 -match "False"){
$Worksheet.Cells($i,4).Interior.ColorIndex = 3
}
}
$name1 = $worksheet.Cells.Item(1,6).Text
$name2 = $worksheet.Cells.Item(1,4).Text
# Formatting
$RangeBold = $Worksheet.Range("A1","C92")
$RangeBold.Select()
$RangeBold.Font.Bold=$True
$RangeBold = $Worksheet.Range("E1","E92")
$RangeBold.Select()
$RangeBold.Font.Bold=$True
$RangeDel = $Worksheet.Range("F1","F92")
$RangeDel.Select()
$RangeDel.Delete()
$RangeBorder = $Worksheet.Range("A1","E86")
$RangeBorder.Select()
$RangeBorder.Borders.LineStyle = 1
$RangeBorder.Borders.Weight = 2
# Footer Margin
worksheet("Sheet1").PageSetup.FooterMargin = _
Application.InchesToPoints(0.5)
# Header Margin
Worksheet("Sheet1").PageSetup.HeaderMargin = _
Application.InchesToPoints(0.5)
# Left Margin
Worksheet("Sheet1").PageSetup.LeftMargin = _
Application.InchesToPoints(0.5)
# Right Margin
Worksheet("Sheet1").PageSetup.RightMargin = _
Application.InchesToPoints(0.5)
$xlsx = "C:\ProgramData\CODESYS\CODESYSHMIWinV3\D5050FE1\PlcLogic\data\$name1-$name2.xlsx"
#Printing Excel Sheet
$xlsx.Visible = $true
$workbook = $xlsx.Workbooks.Open('C:\ProgramData\CODESYS\CODESYSHMIWinV3\D5050FE1\PlcLogic\data\$name1-$name2.xlsx')
$worksheet = $workbook.WorkSheets.Item(1)
$xlsx.ActivePrinter = "808_TOSHIBA5508A on WINFPS01.tld-america.com"
$worksheet.PrintOut(1,4,1)
$xlsx.quit()
# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$Workbook = $excel.Workbooks.open($xlsx)
$excel.Quit()
Remove-Item $csv
Invoke-Item $xlsx
The sheet still prints with this code, just not formatted how I would like. I need the margins to be smaller, and wanted to center the text in each cell. Any thoughts or other resources to used? I have been google searching for hours and am not finding anything.

How to save file without overwrite excel file

I am using EPPlus.dll in Powershell script to convert csv file to xlsx file, but I no have idea how to save file without overwrite existing data.
I have to generate new information from csv file to excel file,
but I have others, manualy created tab which my script always overwrite.
Script looks like this:
$FileNameCSV = "$env:WORKSPACE/file.csv"
$FileNameExcel = "\\folder\file.xlsx "
$DLLPath = "D:\EPPlus.dll"
[Reflection.Assembly]::LoadFile($DLLPath) | Out-Null
$Format = New-object -TypeName OfficeOpenXml.ExcelTextFormat
$Format.Delimiter = ","
$Format.TextQualifier = '"'
$Format.Encoding = [System.Text.Encoding]::UTF8
$Format.SkipLinesBeginning = '0'
$Format.SkipLinesEnd = '1'
$TableStyle = [OfficeOpenXml.Table.TableStyles]::Medium1
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage
$Worksheet = $ExcelPackage.Workbook.Worksheets.Add("CM")
$null=$Worksheet.Cells.LoadFromText((Get-Item $FileNameCSV),$Format,$TableStyle,$true)
$Worksheet.Cells[$Worksheet.Dimension.Address+1].AutoFitColumns()
$Worksheet.Column(3).Style.Numberformat.Format = "dd/mm/yyyy";
$ExcelPackage.SaveAs($FileNameExcel)
Write-Host "CSV File $FileNameCSV converted to Excel file $FileNameExcel"
You need to open the existing file named $FileNameExcel by passing the name to the constructor, probably like this:
$ExcelPackage = New-Object OfficeOpenXml.ExcelPackage($FileNameExcel)
Then, add a new worksheet to this workbook, load the csv into this new worksheet the same way you do it currently, and save the workbook again.

Export as CSV instead of a XLS file

I have a script that places everything nicely into a spread sheet. The problem is, I need it to export as a csv file instead. All the foreach loops are completely baffling me here as far as where to put the export csv functions in the script. If someone could could school me on how to get the fields into a csv file, It would be greatly appreciated.
$date = 0
$date = get-date -format "yyyy-MMM-dd-hhmm"
$date
#New Excel Application
$Excel = New-Object -Com Excel.Application
$Excel.visible = $False
# Create 1 worksheets
$Excel = $Excel.Workbooks.Add()
# Assign each worksheet to a variable and
# name the worksheet.
$Sheet1 = $Excel.Worksheets.Item(1)
$Sheet1.Name = "HH_SERVERS"
#Create Heading for General Sheet
$Sheet1.Cells.Item(1, 1) = "Machine_Name"
$Sheet1.Cells.Item(1, 2) = "OS"
$Sheet1.Cells.Item(1, 3) = "Software"
$Sheet1.Cells.Item(1, 4) = "Vendor"
$Sheet1.Cells.Item(1, 5) = "Version"
$colSheets = ($Sheet1)
foreach ($colorItem in $colSheets)
{
$intRow = 2
$intRowDisk = 2
$intRowSoft = 2
$intRowNet = 2
$WorkBook = $colorItem.UsedRange
$WorkBook.Interior.ColorIndex = 20
$WorkBook.Font.ColorIndex = 11
$WorkBook.Font.Bold = $True
}
#Auto Fit all sheets in the Workbook
foreach ($colorItem in $colSheets)
{
$WorkBook = $colorItem.UsedRange
$WorkBook.EntireColumn.AutoFit()
clear
}
$Servers = get-content "c:\temp\HH_Servers.txt"
foreach ($Server in $Servers)
{
$GenItems2 = gwmi Win32_OperatingSystem -Comp $Server
$Software = gwmi Win32_Product -Comp $Server
# Populate General Sheet(1) with information
foreach ($objItem in $GenItems2)
{
$Sheet1.Cells.Item($intRow, 2) = $objItem.Caption
}
#Populate Software Sheet
foreach ($objItem in $Software)
{
$Sheet1.Cells.Item($intRowSoft, 1) = $Server
$Sheet1.Cells.Item($intRowSoft, 3) = $objItem.Name
$Sheet1.Cells.Item($intRowSoft, 4) = $objItem.Vendor
$Sheet1.Cells.Item($intRowSoft, 5) = $objItem.Version
$intRowSoft = $intRowSoft + 1
}
}
$outputfile = "c:\temp\" + $date.toString() + "-HH_Server_Software"
$Excel.SaveAs($outputfile)
$Excel.Close()
Write-Host "*******************************" -ForegroundColor Green
Write-Host "The Report has been completed." -ForeGroundColor Green
Write-Host "*******************************" -ForegroundColor Green
# ========================================================================
# END of Script
# ==================
You can't save an entire workbook as CSV. You need to save the individual worksheet instead. The file format value for CSV is 6 (don't remember where I found that out though):
$xlCSV = 6
$outputfile = "c:\temp\" + $date.toString() + "-HH_Server_Software.csv"
$Sheet1.SaveAs($outputfile, $xlCSV)
(Tested on Windows 7 with Excel 2013.)
Thanks to #Matt for a comment with a link to the XLFileFormat Enumerations.

Resources