excel 中的一个单元格中包含多行的变量

variable with multiple lines into one cell in excel

我有一个 ps 脚本,其中包含多个“if”语句,用于在选中复选框时输出信息。我将那些 IF 语句分配给了一个变量。如果我打印出变量(在控制台或文本文件中),则数据是正确的。我需要能够将变量写入 excel 电子表格中的单个单元格。我不会让你厌烦整个剧本,而是重要的部分。感谢任何帮助。

function Build_table {
$global:Content =$(
if ($box1.checked -eq $true) {
write-output "box 1 is checked"
write-output "some other text here" }
if ($box2.checked -eq $true) {
write-output "Box 2 is checked" }
) }  #there are several more "if" statements, but they are all similar

我有打开 excel 和 select 正确工作表的标准代码行 很好。

$worksheet.Cells.Item(1,2) = "here is your list"
$worksheet.Cells.Item(2,2) = $Content

我用它用其他变量填充其他单元格,而且一切都很好,因为它们是一行文本。但是对于 $Conent,它不会在单元格中放入任何内容。

打印出来的样例数据$Content:

框 1 已选中

框 3 已选中

方框 3 一些其他文字....

数据行之间没有空格(只是不知道为什么要加双倍行距)

我需要能够将该输出以多行形式插入到适用的单元格中,如图所示。

$content 是一个 aray 字符串。要将其放入单元格中,您需要将其变为单个多行 string.

尝试:

$worksheet.Cells.Item(2,2) = $Content -join [environment]::NewLine