1

我有这个 excel 表,我希望 csv 文件具有相同的格式。有人可以帮我编写一个自动化脚本(将多个 excel 表转换为 csv 文件)吗?

我试过这个脚本,但是卡号的第 16 位变成了零,因为 excel 只能正确读取 15 位。我们可以修改此代码以将多个 excel 工作表转换为 csv 文件吗?

有人可以帮我解决这个问题。

将 Excel 文件转换为 CSV

$xlCSV=6
$Excelfilename = “C:\Temp\file.xlsx”
$CSVfilename = “C:\Temp\file.csv”
$Excel = New-Object -comobject Excel.Application
$Excel.Visible = $False
$Excel.displayalerts=$False
$Workbook = $Excel.Workbooks.Open($ExcelFileName)
$Workbook.SaveAs($CSVfilename,$xlCSV)

$Excel.Quit() If(ps excel){kill -name excel}

4

1 回答 1

0

Excel 在处理 CSV 文件方面确实很特别。
虽然使用该方法时会完整写出 16 位数字SaveAs,但如果您通过双击 csv 文件重新打开它,Excel 会将这些数字转换为数值而不是字符串。

为了强制 Excel解释这些值并简单地将它们视为字符串,您需要在 csv 文件中调整这些值,方法是在它们前面加上一个 TAB 字符。

(这将使该文件对其他应用程序无用..)

当然,您需要知道正确的列标题才能执行此操作。

假设您的 Excel 文件如下所示:

例子

可以看到,我们需要调整的值存放在Number列中

要输出可以双击的 csv 文件以便在 Excel 中打开它们,下面的代码将为您执行此操作:

$xlCSV      = 6
$Excelfiles = 'D:\test.xlsx', 'D:\test2.xlsx'  # an array of files to convert
$ColumnName = 'Number'                         # example, you need to know the column name

# create an Excel COM object
$Excel               = New-Object -comobject Excel.Application
$Excel.Visible       = $False
$Excel.DisplayAlerts = $False

foreach ($fileName in $Excelfiles) {
    $Workbook = $Excel.Workbooks.Open($fileName)
    # use the same file name, but change the extension to .csv for output
    $CSVfile = [System.IO.Path]::ChangeExtension($fileName, 'csv')
    # have Excel save the csv file
    $Workbook.SaveAs($CSVfile, $xlCSV)
    $Workbook.Close($false)
}

# close excel and clean up the used COM objects
$Excel.Quit()
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Workbook)
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($Excel)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()

# now import the csv files just created and update the card number
# column by prefixing the value with a TAB character ("`t").
# this will effectively force Excel NOT to interpret the value as numeric.
# you better not do this inside the same loop, because Excel keeps a lock
# on outputted csv files there.
foreach ($fileName in $Excelfiles) {
    # use the same file name, but change the extension to .csv for output
    $CSVfile = [System.IO.Path]::ChangeExtension($fileName, 'csv')

    # the '-UseCulture' switch makes sure the same delimiter character is used
    $csv = Import-Csv -Path $CSVfile -UseCulture
    foreach ($item in $csv) { $item.$ColumnName = "`t" + $item.$ColumnName }
    # re-save the csv file with updates values
    $csv | Export-Csv -Path $CSVfile -UseCulture -NoTypeInformation
}
于 2019-12-06T16:00:30.327 回答