Hi PowerShell,
I am facing some issues with convert csv to xlsx using c#.
If I am using PowerShell script without called through a C#. That is fine! But now I am written codes in powershell called through a C#.
here is my sample program code as below:
using (PowerShell PowerShellInstance = PowerShell.Create())
{
string test = "Function Release-Ref ($ref) { \n" +
"([System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$ref) -gt 0) \n" +
"[System.GC]::Collect() \n" +
"[System.GC]::WaitForPendingFinalizers() \n" +
"} \n" +
"Function ConvertCSV-ToExcel { \n" +
"[CmdletBinding(SupportsShouldProcess = $True, ConfirmImpact = 'low', DefaultParameterSetName = 'file')] \n" +
"Param ([Parameter(ValueFromPipeline=$True, Position=0, Mandatory=$True, HelpMessage=\"Name of CSV/s to import\")] \n" +
"[ValidateNotNullOrEmpty()] \n" +
"[array]$inputfile, [Parameter( ValueFromPipeline=$False, Position=1, Mandatory=$True, HelpMessage=\"Name of excel file output\")] \n" +
"[ValidateNotNullOrEmpty()] \n" +
"[string]$output \n" +
") \n" +
"Begin { \n" +
"[regex]$regex = \"^\\w\\:\\\" \n" +
"$count = ($inputfile.count -1) \n" +
"$excel = new-object -com excel.application \n" +
"$excel.DisplayAlerts = $False \n" +
"$excel.Visible = $False \n" +
"$workbook = $excel.workbooks.Add() \n" +
"$workbook.worksheets.add() \n" +
"$workbook.worksheets.add() \n" +
"$workbook.worksheets.Item(1).delete() \n" +
"$workbook.worksheets.Item(1).delete() \n" +
"$i = 1 \n" +
"} \n" +
"Process { \n" +
"ForEach ($input in $inputfile) { \n" +
"If ($i -gt 1) { $workbook.worksheets.Add() | Out-Null } \n" +
"$worksheet = $workbook.worksheets.Item(1) \n" +
"$worksheet.name = \"$((GCI $input).basename)\" \n" +
"If ($regex.ismatch($input)) { $tempcsv = $excel.Workbooks.Open($input)} \n" +
"ElseIf ($regex.ismatch(\"$($input.fullname)\")) { $tempcsv = $excel.Workbooks.Open(\"$($input.fullname)\") } \n" +
"Else {$tempcsv = $excel.Workbooks.Open(\"$($pwd)\\$input\")} \n" +
"$tempsheet = $tempcsv.Worksheets.Item(1) \n" +
"$tempSheet.UsedRange.Copy() | Out-Null \n" +
"$worksheet.Paste() \n" +
"$tempcsv.close() \n" +
"$range = $worksheet.UsedRange \n" +
"$range.EntireColumn.Autofit() | out-null \n" +
"$i++ \n" +
"} \n" +
"} \n" +
"End { \n" +
"$workbook.saveas(\"$pwd\\$output\") \n" +
"Write-Host -Fore Green \"File saved to $pwd\\$output\" \n" +
"$excel.quit() \n" +
"$a = Release-Ref($range)\n" +
"}\n" +
"} \n" +
"ConvertCSV-ToExcel -inputfile .\\Demo.csv -output \"demo.xlsx\" ";
PowerShellInstance.AddScript(test);
PowerShellInstance.Invoke();
}
Where Demo.csv has data so i opened demo.xlsx and its empty after i build/Run.
Ref:
http://blogs.msdn.com/b/kebab/archive/2014/04/28/executing-powershell-scripts-from-c.aspx
https://gallery.technet.microsoft.com/scriptcenter/7c56c444-2476-4625-b1d9-821f30280e44/
http://learn-powershell.net/2010/09/04/converting-csv-file-or-files-into-an-excel-workbook/
Any Idea?
I am waiting for your response.
Thanks