對于一個專案,我需要將資料從 .xlsm 檔案資料匯出到 CSV 檔案,然后使用 powershell 處理它。我手動進行匯出。在原始檔案中,標頭中有換行符,這些換行符也傳輸到 CSV 檔案中。我的問題:
- 我可以使用 Powershell 從 .xlsm 匯出特定作業表嗎?
- 如何用空格替換換行符?
附件是原始 .xlsm 檔案的示例。

更新:不幸的是,我不知道如何上傳檔案。以下是示例 CSV 檔案的內容:
Host name;Computer name old;IP-addr.;"IP-addr.
free?";"Subnetmask
CIDR Suffix";Static DNS entry;DNS alias;"vCPU Number
[Units]";"RAM
[GB]";"Boot disk
[GB]";;;;;;;;
Broadcast;;172.225.145.0;Net;26;;;;;;;;;;;;;
Gateway;;172.225.145.1;Net;26;;;;;;;;;;;;;
Server125;;172.225.145.2;yes;26;;;;;;;;;;;;;
Server126;;172.225.145.3;yes;26;;;;;;;;;;;;;
Server127;;172.225.145.4;yes;26;;;;;;;;;;;;;
Server128;;172.225.145.5;no;26;;;;;;;;;;;;;
CSV 檔案的 Notepad 螢屏截圖

uj5u.com熱心網友回復:
我可以使用 Powershell 從 .xlsm 匯出特定作業表嗎?
使用可以安裝的ImportExcel模塊Install-Module ImportExcel。
有關示例,請參見此答案。
如何用空格替換換行符?
一個簡單(盡管效率不高)的方法是:
Import-Csv首先使用orImport-Excel(從模塊)匯入 CSVImportExcel- 這適用于具有嵌入換行符的標題欄位,只要這些欄位包含在"..."然后處理生成的
[pscustomobject]實體并將它們替換為新構造的變體,其屬性名稱的換行符替換為空格。
Import-Csv yourFile.csv | # parse the CSV file into [pscustomobject]s
ForEach-Object { # process each object
$oht = [ordered] @{} # create an aux. ordered hashtable
foreach ($p in $_.psobject.Properties) { # loop over the object's properties
# add a name-value entry with the modified column (property) name.
$oht[($p.Name -replace '\s ', ' ')] = $p.Value
}
[pscustomobject] $oht # convert the hashtable to [pscustomobject] and output
}
將上述內容通過管道傳輸到Export-Csv或Export-Excel(來自ImportExcel模塊),以便將資料重新匯出回檔案,將其傳輸到另一個命令,或在變數中捕獲轉換后的物件 ( $objects = Import-Csv ...)
筆記:
-replace用于替換空白字符的任何非空運行 ()。(\s) 帶有一個空格 (' ')。這確保了序列<space><LF>被單個空格替換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513259.html
