简体   繁体   中英

How to modify excel data and export to text file using PowerShell script?

First time poster here. Apologies if I am not following best practices for posting this question.

I am very new to scripting and PowerShell.

Problem:

I have data in an excel sheet in this format.

Excel Data Image Link

1

I want to modify and export this data into a text file. In this format.

Required Output Image Link

2

Till now I have tried to modify the excel data by accessing each cell. To access each cell I am using a similar code mentioned below.

 for (($i = 1); $i -lt 4; $i++)
{
$column=$ExcelWorkSheet.Columns.Item(1).Rows.Item($i).Text
$dataType=$ExcelWorkSheet.Columns.Item(2).Rows.Item($i).Text

$c1=("`"" + "$column" + "`""+":")
$c2=("`"" + "$dataType" + "`"" + ",")
$ExcelWorkSheet.Columns.Item(1).Rows.Item($i).Value=$c1
$ExcelWorkSheet.Columns.Item(2).Rows.Item($i).Value=$c2
}

I am still not sure if this is the correct way to go.

what would be the best way to solve this?

Just want to understand what I should do to solve this problem. I am not looking for the exact code.

Step by step instructions or some resources would be helpful.

Thanks!

This might help... maybe...

# Import Stuff
$Data = Import-Csv -Path .\Desktop\data.csv

# New Array 
$Output = @()

# Run through Unique Owners
foreach ($Owner in ($Data | Select-Object OWNER -Unique)) {
    $Lines = $Data | Where-Object {$_.OWNER -eq $Owner.OWNER}
    # Lazy way to do a bit of checking, if same then use it or Break
    if ($Lines[0].TABLE_NAME -eq $Lines[1].TABLE_NAME) {
        $Out_TableName = $Lines[0].TABLE_NAME
        # ID and NAME data
        $Out_ID = $Lines | Where-Object {$_.COLUMN_NAME -eq "ID"} | Select-Object COLUMN_NAME, DATA_TYPE, DATA_LENGTH
        $Out_NAME = $Lines | Where-Object {$_.COLUMN_NAME -eq "NAME"} | Select-Object COLUMN_NAME, DATA_TYPE, DATA_LENGTH
    } else {
        # Show the user that something
        Write-Host "Problem with Owner ""$($Owner.OWNER)"" Data?!" -ForegroundColor Red
        Break
    }
    # Output into the array in format
    $Output += @"
"$($Owner.OWNER).$($Out_TableName)":{
"$($Out_ID.COLUMN_NAME)": "$($Out_ID.DATA_TYPE) ($($Out_ID.DATA_LENGTH))",
"$($Out_NAME.COLUMN_NAME)": "$($Out_NAME.DATA_TYPE) ($($Out_NAME.DATA_LENGTH))"
}

"@
}

# Put Output in a text file
$Output | Set-Content .\Desktop\output.txt -Force

I should add, that I had your data in a CSV like this...

OWNER,TABLE_NAME,COLUMN_NAME,DATA_TYPE,DATA_LENGTH
A,Employee,ID,NUMBER,22
A,Employee,NAME,VARCHAR2,22
B,Department,ID,NUMBER,23
B,Department,NAME,VARCHAR2,24

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM