【问题标题】:How can I extract a particular worksheet in an xlsx spreadsheet as a text file?如何将 xlsx 电子表格中的特定工作表提取为文本文件?
【发布时间】:2021-10-26 20:10:42
【问题描述】:

我需要从几个不同的 xlsx 电子表格中提取一个名为 Approval_Logs 的工作表并将它们转换为文本文件。

我已经在 linux 下使用 gnumeric 的 ssconvert 命令完成了这项工作,但我还没有找到在 Windows 中执行此操作的方法,我正在尝试制作一个用户友好的 powershell 脚本来自动执行此任务。

谢谢!

【问题讨论】:

  • 您会接受 CSV 文件作为文本文件吗?
  • 是的,那很好。

标签: excel powershell


【解决方案1】:

下面的 sn-p 可能会给你一个起点。

您可能需要在硬盘上找到 Interop dll 的正确路径,然后调整 add-type cmdlet。

$dir 是工作簿从中打开和写入的目录。

$dir = convert-path ~/ZZZ/Excel/Export-CSV/

add-type -path 'C:\Program Files (x86)\Microsoft Office\Office16\DCF\Microsoft.Office.Interop.Excel.dll'

$xls = new-object Microsoft.Office.Interop.Excel.ApplicationClass
$xls.visible       = $true
$xls.displayAlerts = $false

foreach ($wbFile in get-childItem $dir\*.xls*) {
   $wb = $xls.workbooks.open($wbFile.fullName)

   try {
      $sh = $wb.sheets('Approval_Logs')
   }
   catch {
      if ($_.exception.message -match 'Invalid index.') {
         write-host "Expected sheet not found in $($wb.name)"
         $wb.close()
         continue
      }
      throw $_
   }

   $sh.select()

   $csvFile = "${dir}$($wbFile.basename).csv"
   $wb.saveAs($csvFile, 6, $false)
   write-host "$csvFile was saved"

   $wb.close()

}

$xls.quit()

【讨论】:

  • 太棒了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-05
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多