【问题标题】:Importing notepad data to excel (difficult split)将记事本数据导入excel(难拆分)
【发布时间】:2021-08-27 20:01:09
【问题描述】:

我想将此数据从记事本传输到 Excel 并将其拆分为列 但问题是数据(我没有这样做)没有在分隔符上拆分。 所有数据看起来都像下面这个的变体

Header: "a" "b" "c" "d" "e" ... "n"
rows:   "1" "sgvgs-dvfds" "" "0.0" "d'/.d" ... "m"

所有内容都包含在引号中。有没有人知道如何通过 excel 甚至通过 powershell 实现它?

【问题讨论】:

  • 我可能遗漏了一些东西,但不是空格“”作为您显示的数据中的分隔符(假设“行”中的列数与“标题”中的列数相同) ?
  • 文本文件真的是这样的吗?在每行前面标注Header:rows: ?如果没有,请在记事本中打开文件并复制前几行。将其粘贴到问题中。
  • ""
  • 请看我的编辑
  • 如前所述,对我来说,它看起来像是空格。即使有两个引号,其中没有任何内容。你为什么不试试excel中的空格分隔符

标签: excel powershell notepad data-transform


【解决方案1】:

如果文件确实是这样,您可以将其转换为 Excel 可以理解的 CSV 格式,如下所示:

(Get-Content -Path 'D:\Test\WeirdFormat.csv' -Raw) -replace '(?m)^(Header|rows):\s+' | 
ConvertFrom-Csv -Delimiter ' ' | 
Export-Csv -Path 'D:\Test\ExcelCanOpenThis.csv' -UseCulture -NoTypeInformation

您现在应该有一个 csv 文件,如果您双击它,它将在 Excel 中打开。

如果不是,请提供一个更好的输入文件示例,准确地显示它的样子。

正则表达式详细信息:

(?m)               Match the remainder of the regex with the options: ^ and $ match at line breaks (m)
^                  Assert position at the beginning of a line (at beginning of the string or after a line break character)
(                  Match the regular expression below and capture its match into backreference number 1
                   Match either the regular expression below (attempting the next alternative only if this one fails)
      Header       Match the characters “Header” literally
   |               Or match regular expression number 2 below (the entire group fails if this one fails to match)
      rows         Match the characters “rows” literally
)                 
:                  Match the character “:” literally
\s                 Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
   +               Between one and unlimited times, as many times as possible, giving back as needed (greedy)


根据您的评论,Header:rows: 不在文件中。
这使它变得更容易并且只需执行以下操作:

Import-Csv -Path 'D:\Test\InputFile.csv -Delimiter ' ' | 
Export-Csv -Path 'D:\Test\ExcelCanOpenThis.csv' -UseCulture -NoTypeInformation

【讨论】:

    【解决方案2】:

    我们是不是想多了?原始发布者想要的最终目的地是 Excel,那么为什么要涉及 PowerShell?

    使用 Excel:

    1. 在“数据”选项卡上选择“来自文本/CSV”
    2. 选择并打开文件
    3. 在打开的对话框中,将分隔符设置为空格,然后单击加载
    4. Bingo,OP 想要的 Excel 数据(它可以正确处理空列)

    【讨论】:

    • 同意。既然有简单的解决方案,为什么还要选择复杂的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-17
    相关资源
    最近更新 更多