You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本调整Excel列格式为四位小数并导出CSV的问题排查

解决Excel转CSV时小数丢失的问题

你的核心问题出在两个地方:列索引的变化导致格式设置失效,以及Excel CSV导出的默认行为不强制保留格式化后的显示文本。让我一步步帮你修正脚本:

问题分析

  1. 列位置偏移错误:你先给H列设置了格式,随后删除了第一列(A列),这会让所有列左移一位——原来的H列变成了G列,你的格式设置根本没作用到最终的目标列上。
  2. CSV导出逻辑:Excel默认用SaveAs xlCSV导出时,会优先导出单元格的实际存储值,而不是格式化后的显示文本。如果你的单元格实际值是14.55,CSV里只会显示14.55;如果单元格已经被格式设置或公式四舍五入为15,仅改格式也无法恢复小数。

修改后的完整脚本

# Set Folder Paths
$processFolder = "C:\Powershell\Excel\Process\"
$outFolder = "C:\Powershell\In\"
$archiveFolder = "C:\Powershell\Excel\Archive\"
$errorFolder = "C:\Powershell\Excel\Error\"

# Get all .xlsx files in Process folder and loop
$ens = Get-ChildItem $processFolder -filter *.xlsx
foreach($e in $ens) {
    & {
        $sourceFile = Join-Path $processFolder "$($e.Basename).xlsx"
        $outFile = Join-Path $outFolder "$($e.Basename)_$([DateTime]::Now.ToString("yyyyMMdd-HHmmss")).csv"
        $archiveFile = Join-Path $archiveFolder "$($e.Basename)_processed_$([DateTime]::Now.ToString("yyyyMMdd-HHmmss")).xlsx"
        $errorFile = Join-Path $errorFolder "$($e.Basename)_error_$([DateTime]::Now.ToString("yyyyMMdd-HHmmss")).xlsx"
        
        $excelApplication = New-Object -ComObject Excel.Application
        try {
            $excelApplication.Visible = $false
            $excelApplication.DisplayAlerts = $false
            $workbook = $excelApplication.Workbooks.Open($sourceFile)
            $sheet = $workbook.Sheets.Item("SUMMARY")
            
            # 先删除不需要的行和列,避免列位置偏移
            [void]$sheet.Cells.Item(1, 1).EntireColumn.Delete() # 删除第一列
            for ($i=1; $i -le 12; $i++) {
                [void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # 删除前12行
            }
            
            # 原来的H列现在是第7列(G列),设置四位小数格式
            $targetColumn = $sheet.Columns(7) # 也可以用 $sheet.Columns("G")
            $targetColumn.NumberFormat = "0.0000"
            
            # 可选:强制CSV导出带四位小数的文本(包括末尾的0)
            $usedRange = $sheet.UsedRange
            foreach ($cell in $targetColumn.Cells) {
                if ($cell.Row -ge $usedRange.Row -and $cell.Value -ne $null) {
                    # 四舍五入到四位小数并转为文本格式
                    $cell.Value = [math]::Round($cell.Value, 4).ToString("0.0000")
                    $cell.NumberFormat = "@" # 设置为文本格式保留末尾0
                }
            }
            
            # 保存为CSV
            $workbook.SaveAs($outFile, [Microsoft.Office.Interop.Excel.XlFileFormat]::xlCSV)
            $workbook.Close()
            
            Move-Item -Path $sourceFile -Destination $archiveFile
        }
        catch {
            Write-Error $_.Exception.Message
            Copy-Item -Path $sourceFile -Destination $errorFile
        }
        finally {
            # 彻底清理Excel COM对象,避免进程残留
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($sheet) | Out-Null
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbook) | Out-Null
            $excelApplication.Quit()
            [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelApplication) | Out-Null
            [GC]::Collect()
            [GC]::WaitForPendingFinalizers()
        }
    }
}

关键修改点说明

  1. 调整操作顺序:先删除冗余的行和列,再设置目标列的格式,确保列索引正确。
  2. 修正列引用:用列索引7替代字母H,避免列位置变化导致的格式失效。
  3. 强制保留四位小数:通过遍历单元格将数值转为带四位小数的文本,确保CSV导出时显示14.5500而非14.55或15。
  4. COM对象清理:添加了更彻底的进程清理代码,防止Excel后台进程残留占用资源。

内容的提问来源于stack exchange,提问作者Roger Clerkwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 17:42:37