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.
Related
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'm trying to get data from an executable excel file (which is an excel file compressed and wrapped into an .exe) without success using PowerShell. I can open it, but I can't get the values stored in it.
I've been able to get data from binary excel files though (.xlsb).
$FilePath = "d:\database\temp.xlsb"
$SheetName = "NDC"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($FilePath)
$WorkSheet = $Workbook.sheets.item($SheetName)
$value = $Worksheet.Range("A1").Text
Then, my question is, is it possible to open the excel exe file and save the file with a format that can be accessed with PowerShell?
I have this CSV file I generate using Export-CSV. Everything is fine with it but it display like this when opening in Excel because the cells are not formatted as TEXT:
I want to force open the CSV with the cells all set to TEXT like you can do manually with the interface.
Is there a way to automate that with PowerShell, opening the CSV in Excel with cells formatted as text?
There is a little trick you can use - convert your data to html, and save with "xls" extention. For example:
Get-Process | convertto-html | Out-File csv2.xls
You'll see a warning when opening it, just click OK.
You can suppress that warning message by adding extra key in registry:
open regedit
HKEY_CURRENT_USER\Software\Microsoft\Office\15.0\Excel\Security
Create a new DWORD with name ExtensionHardening and value 0
Found a very good way to make it happen!
After generating your CSV file, here is how to automatically load it into Excel with AutoFit column width and TEXT format for cells :) :
$Fichier = "PATH_TO_CSV.csv"
$objExcel = New-Object -ComObject Excel.Application
$WorkBook = $objExcel.Workbooks.Open($Fichier)
$WorkSheet = $WorkBook.worksheets.item(1)
$objExcel.Visible = $true
$Range = $worksheet.UsedRange.Cells
$range.NumberFormat = "#"
$WorkSheet.Columns("A:B").AutoFit()
I have the following code but I am trying to get it to prompt user with a dynamic dialog box to get the output file to "save as".
$pathtsv = "c:\test.txt"
$pathxlsx = "c:\NBP ESP-152 REV F TEMPLATE.xlsx"
$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible=$true
$Workbook = $Excel.Workbooks.Open($pathxlsx) # Open Template
$TempWorkbook = $Excel.Workbooks.Opentext($pathtsv) # Open text file in excel
$temp = $excel.Workbooks.Item(2) #select workbook with text
$temp = $temp.Worksheets.Item(1) #select text worksheet
$CopyRange = $temp.Range("A1:G8") #set range
$CopyRange.Copy() #copy data
$workbooksheet = $Workbook.Worksheets.Item(1)#sets doc to copy to
$Workbooksheet.activate()
$PasteRange = $workbooksheet.Range("A3:J10") #sets range
$workbooksheet.Paste($PasteRange)#paste data
#save and close the workbook
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()
So I tried adding in:
$SaveFileDialog = New-Object windows.forms.savefiledialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
but it does not seem to be working. Not sure why, maybe because I am still newbish to powershell scripting. I just want to get it to end on the save as dialog box, would be fine. Do I have to cut the end of the original out? (IE. does this get cut out?
$Workbook.Close($true)
$Excel.Quit()
while( [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)){}
[gc]::collect()
[gc]::WaitForPendingFinalizers()
)
You need to do a few things to make this work. First, add a reference to System.Windows.Forms
Add-Type -AssemblyName System.Windows.Forms
After your copy/paste operations create the dialog and set a couple properties
$SaveFileDialog = New-Object System.Windows.Forms.SaveFileDialog
$SaveFileDialog.initialDirectory = [System.IO.Directory]::GetCurrentDirectory()
$SaveFileDialog.Filter = 'All files (*.*)|*.*'
This is where you will need to decide what you want to do when showing the dialog. Do you allow the user to cancel, how do you handle empty paths, incorrect extensions, etc... For the sake of example, I am going to simply continue to show it until a path is chosen. I am not endorsing this as a good choice.
$dialogResult = $null
while($dialogResult -ne "OK"){
$dialogResult = $SaveFileDialog.ShowDialog()
}
You can then access the selected path with the FileName property and perform and checks needed on it
$SaveFileDialog.FileName
Pass this to the excel workbook's SaveAs method. See this answer for details on this method https://stackoverflow.com/a/25289878/3594883
$WorkBook.SaveAs($SaveFileDialog.FileName, 51, [Type]::Missing, [Type]::Missing, $false, $false, 1, 2)
Finally close your workbook and excel. Perform cleanup etc.
I have a file which file extension is .xls, but the weird thing is when save as, the default is go to html file.
This caused a problem when I'm using my powershell script to perform some action on the file and saved it as xls file. The result is the script generate one xls file and one folder which contain html file. Is there a way to fix this issues ? I just want to save the file as xls file wihout any html files. Any helps are much appreciated.
Here the code that I use to save file as .xls
Function RenameTab ($ExcelFileName, $OutLoc)
{
$excelFile = "D:\Projects\" + $excelFileName + ".xls"
$xldoc = New-Object -ComObject "Excel.Application"
$xldoc.Visible = $false
$xldoc.DisplayAlerts = $false
$workbook = $xldoc.Workbooks.Open($excelFile)
foreach ($worksheet in $workbook.Worksheets)
{
$n = $ExcelFileName ##+ "_" + $worksheet.Name
$worksheet = $workbook.worksheets.item(1)
$worksheet.name = "Sheet1"
$workbook.SaveAs($OutLoc + $n + ".xlsx")
$workbook.Close()
}
$xldoc.Quit()
}
When you call SaveAs, you should really specify the file format.
According to the documentation for SaveAs, it would be the second argument, so the corrected line would be:
$workbook.SaveAs($OutLoc + $n + ".xlsx", 51) # 51 = xlOpenXMLWorkbook
I don't have all that much experience with COM interaction, but you might be able to use the enumeration directly somehow and make the line similar to:
$workbook.SaveAs($OutLoc + $n + ".xlsx", $xldoc.XlFileFormat.xlOpenXMLWorkbook)