excel - 如何将XML中的数组值插入Excel中行的每个顺序单元格,为每一行循环?
问题描述
我有一个 XML 文件,其中包含给定月份给定日期的每个小时的值。
例如,开始日期/时间将是给定月份的上午 12:00 的 15 日,结束日期/时间将是下个月的上午 12:00 的 15 日。
XML 文件示例:
<Generated>
<Entry>
<ID>76492055</ID>
<Date>2018-09-15</Date>
<Time>00:00:00</Time>
<Income>746557.0993</Income>
</Entry>
<Entry>
<ID>76492055</ID>
<Date>2018-09-15</Date>
<Time>01:00:00</Time>
<Income>815445.5908</Income>
</Entry>
<Entry>
<ID>76492055</ID>
<Date>2018-09-15</Date>
<Time>02:00:00</Time>
<Income>1190228.1310</Income>
</Entry>
<Entry>
<ID>76492055</ID>
<Date>2018-09-15</Date>
<Time>03:00:00</Time>
<Income>932243.0268</Income>
</Entry>
<Entry>
<ID>76492055</ID>
<Date>2018-09-15</Date>
<Time>04:00:00</Time>
<Income>709702.1181</Income>
</Entry>
...
</Generated>
我当然可以在 PowerShell 中使用以下代码很好地显示数据:
$xml = [System.Xml.XmlDocument](Get-Content "TheXMLFile.xml")
[datetime]$EndDate = (Get-Date).AddMonths(0).ToString("yyyy-MM-15")
[datetime]$StartDate = (Get-Date).AddMonths(-1).ToString("yyyy-MM-15")
$IncomeDates = 0..(($EndDate - $StartDate).days-1) | % {
$StartDate.AddDays($_).ToShortDateString() }
foreach ($IncomeDate in $IncomeDates) {
$xml.Generated.Entry | Where {$_.Date -eq $IncomeDate} | Select ID,Date,Time,Income
}
但是,我需要让 PowerShell 提取该月给定日期(每小时)的 XML 数据,并将其插入目标 Excel 工作表中该行(当天)的每个连续单元格中。
目标工作表示例:
解决方案
假设您在电子表格中已经有顶行和左列,这将读取 XML,打开电子表格,读取日期范围,根据该日期范围创建对象数组,从 XML 填充数据,然后粘贴它进入电子表格。
$xml = [System.Xml.XmlDocument](Get-Content "TheXMLFile.xml")
$XL = New-Object -ComObject Excel.Application
$WB = $XL.workbooks.open('C:\Path\To\Spreadsheet.xls')
$DateRange = $WB.ActiveSheet.UsedRange.Columns.Item(1).Cells|% Text|Select -skip 1
# Create a hashtable representing a blank day
$BlankDay = [ordered]@{}
0..23|ForEach{$Blankday.Add(("{0}:00:00" -f "$_".Padleft(2,'0')),$null)}
# Build Hashtable to track all days as objects based off the blank day hashtable
$DataHash = [ordered]@{}
$DateRange | ForEach-Object{ $DataHash.add($_,[pscustomobject]$BlankDay) }
# Update each day with data from the XML
$xml.Generated.Entry | Where{$_.date -in $DateRange} | ForEach-Object {
$DataHash[$_.Date]."$($_.Time)" = $_.Income
}
# Convert the data to a tab delimited CSV, skipping the header row, and copy it to the clipboard
$DataHash.Values|convertto-csv -del "`t" -notype|Select -Skip 1 | clip
# Paste it into cell B2
$WB.ActiveSheet.Rows.Item(2).Cells.Item(2).PasteSpecial()
推荐阅读
- javascript - 下载完成后 Django 更新模板
- javascript - 在反应中重定向到主页时出错
- rx-java - rxjava 过滤流中的项目与流中的任何其他过滤器不匹配
- amazon-web-services - 通过 ec2 上的 curl 获取实例名称?
- spring - 春季批处理中不想要 JOB_EXECUTION_PARAMS
- python - 如何根据条件将数据框中的一列切成多个系列
- omnet++ - 使用 Venes_inet 从 aodvRouter 向 adhocHost 发送消息时出错
- vue.js - 如何在换页的同时不停顿地听音乐?
- python-3.x - 如何在每行之后插入每组的最后一行
- javascript - nativescript-vue 应用程序中的 Laravel 身份验证,有人做过吗?