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.
Related
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()
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();
}
I was searching for a simple and fast option to export an existing DataTable-object via Powershell into an Excel file.
At the end I came up with this code. I hope it helps others with same challenge:
# get XML-schema and XML-data from the table:
$schema = [System.IO.StringWriter]::new()
$myTable.WriteXmlSchema($schema)
$data = [System.IO.StringWriter]::new()
$myTable.WriteXml($data)
# start Excel and prepare some objects:
$xls = New-Object -Comobject Excel.Application
$xls.DisplayAlerts = $false
$xls.Visible = $false
$book = $xls.Workbooks.Add()
$sheet = $book.Worksheets[1]
$range = $sheet.Range("A1")
# import the data and save the file:
$map = $book.XmlMaps.Add($schema)
[void]$book.XmlImportXml($data, $map, $true, $range)
$book.SaveAs("c:\temp\test.xlsx", 51)
$xls.Quit()
I need to split and save an excel file based on the values of the first column via a powershell script. Here is how the excel file is build up (app 30.000 rows)
´´´Column1 # Column2 # Column3´´´
´´´AA # data # data # data´´´
´´´AA # data # data # data´´´
´´´AB # data # data # data´´´
´´´AC # data # data # data´´´
´´´AC # data # data # data´´´
The result should be multiple files with filenames AA.xlxs, AB.xlxs, AC.xlxs and of course the according rows data.
What I have so far is the following code:
$objexcel = New-Object -ComObject Excel.Application
$wb = $objexcel.WorkBooks.Open("C:\Test.xlsx")
$objexcel.Visible = $true
$objexcel.DisplayAlerts = $False
$ws = $wb.Worksheets.Item(1)
$doc = $ws.Range("A:A")
foreach ($doc in $docs) {
$newfile,$objexcel = $objexcel.where({$doc -eq $doc})
$newfile | Export-Excel "C:\$doc.xlxs"
}
It just opens the file, but nothing happens.
It would be great if some coder could have a look at the code or provide a working one.
Thanks in advance.
Following is a working code that will iterate through unique elements in column one and make a copy of it in a new spreadsheet and save it.
Function Create-Excel-Spreadsheet {
Param($NameOfSpreadsheet)
# open excel
$excel = New-Object -ComObject excel.application
$excel.visible = $true
# add a worksheet
$workbook = $excel.Workbooks.Add()
$xl_wksht= $workbook.Worksheets.Item(1)
$xl_wksht.Name = $NameOfSpreadsheet
return $workbook
}
$objexcel = New-Object -ComObject Excel.Application
$wb = $objexcel.WorkBooks.Open("C:\Temp\Test.xlsx") # Changing path for test.xlsx file.
$objexcel.Visible = $true
$objexcel.DisplayAlerts = $False
$ws = $wb.Worksheets.Item(1)
$usedRange = $ws.UsedRange
$usedRange.AutoFilter()
$totalRows = $usedRange.Rows.Count
$rangeForUnique = $usedRange.Offset(1, 0).Resize($UsedRange.Rows.Count-1)
[string[]]$UniqueListOfRowValues = $rangeForUnique.Columns.Item(1).Value2 | sort -Unique
for ($i = 0; $i -lt $UniqueListOfRowValues.Count; $i++) {
$newRange = $usedRange.AutoFilter(1, $UniqueListOfRowValues[$i])
$workbook = Create-Excel-Spreadsheet $UniqueListOfRowValues[$i]
$wksheet = $workbook.Worksheets.Item(1)
$range = $ws.UsedRange.Cells
$range.Copy()
$wksheet.Paste($wksheet.Range("A1"))
$workbook.SaveAs("C:\temp\" + $UniqueListOfRowValues[$i], $xlFixedFormat)
$workbook.Close()
}
Reason nothing is happening is because you are iterating over $docs which does not contain any elements. It is currently null.
When you make a reference to look up the data, you are using $objexcel, but thats your excel application.. not the worksheet that you want to iterate over. Use $as for accessing the worksheet.
You need to iterate over Cells of your $ws and take the data when cells.Item(x, 0) and create a new file based on that with values in other two columns.
Link to example on SO -> Create and Update excel file
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.