我正在嘗試將 CSV 檔案匯入 Excel。有很多關于如何執行此操作的示例,其中大多數示例讓您在 Excel 中打開 CSV,然后將資料復制出來,然后將其粘貼到作業簿中您想要的任何位置。我正在這樣做,并且效果很好......直到你有一個列,其中有帶前導零的欄位并且 Excel 截斷前導零,所以我添加了一個命令來設定零的數量:
$sh1_wb1.Range("L:L").NumberFormat = "000000000"
這似乎作業得很好......但是當另一個系統正在處理此作業表時,它看不到前導零。當我打開作業表并單擊該欄位時,前導零丟失了。(另一個系統看到的是單元格中的實際值,而不是顯示的值。)
換句話說,即使我看到:
000012345,但當我實際點擊單元格時,它會顯示那里是什么12345。
我知道發生的事情是,當我在 Excel 中打開 .csv(進行復制)時,Excel 會洗掉前導零。這只是 Excel 所做的事情。
我嘗試通過遍歷所有單元格并從 .csv 檔案中單獨移動它們來構建 Excel 作業表,但該程序非常緩慢。這是我用來執行此操作的代碼。它有效,但每個 Excel 行大約需要 5 秒,我每個作業表有 30,000 行(進入需要填充大約 15 個選項卡的 Excel,每個選項卡有 30,000 行),所以即使這有效,也需要大約 41 小時處理一張紙。:
(
$inputfile = $csvpath
$outputfile = $xlpath
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)
$ws.Cells.NumberFormat = "@"
write-host "Opening $inputfile"
$i = 1
Import-Csv $inputfile | Foreach-Object {
$j = 1
foreach ($prop in $_.PSObject.Properties)
{
if ($i -eq 1) {
$ws.Cells.Item($i, $j).value = $prop.Name
} else {
$ws.Cells.Item($i, $j).value = $prop.Value
}
$j
}
$i
}
$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"
我發現有效(手動)將帶有前導零的數值的 .csv 檔案“正確地”匯入 Excel 的唯一方法是將其作為資料源連接,并在匯入之前將其轉換為該列 Text .
有誰知道是否可以使用 PowerShell 將某些列的格式值修改為 Import Text into Excel?
非常感謝您的任何建議或幫助!
uj5u.com熱心網友回復:
如果您不希望 Excel 將值視為數字(忘記格式化,格式化只是為了顯示目的而不是實際值),您可以NumberFormat在粘貼資料之前將列設定為文本,然后它不會' t 去除任何前導零。就像是:
$inputfile = $csvpath
$outputfile = $xlpath
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $false
$wb = $excel.Workbooks.Add()
$ws = $wb.Sheets.Item(1)
$ws.Cells.NumberFormat = "@"
write-host "Opening $inputfile"
$i = 1
Import-Csv $inputfile|ConvertTo-Csv -NoTypeInformation -Delimiter "`t"|clip
$excel.ActiveCell.PasteSpecial()
$wb.SaveAs($outputfile,51)
$wb.Close()
$excel.Quit()
write-output "Success"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/535850.html
標籤:擅长电源外壳格式文件
