简体   繁体   English

使用PowerShell将CSV导入Excel

[英]Import csv to excel using powershell

I'm trying to import a .txt file which is comma-separated. 我正在尝试导入以逗号分隔的.txt文件。 It gets imported. 它被导入。 But excel doesn't seem to understand that it is, comma-separated. 但是excel似乎不了解它是用逗号分隔的。 It displays all in the same column. 它将全部显示在同一列中。

[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $false
$xl.Workbooks.OpenText($importcsv)
$xl.DisplayAlerts = $false
[threading.thread]::CurrentThread.CurrentCulture = 'en-US'
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()

Any suggestions? 有什么建议么? Thanks. 谢谢。

You have two options. 您有两个选择。 One, if your file extension is .csv instead of .txt , it would work as is. 一种,如果您的文件扩展名是.csv而不是.txt ,它将按原样工作。 The second option, make sure you pass $True for the comma-delimiter parameter, like so: 第二个选项,确保为逗号分隔符参数传递$True ,如下所示:

$xl.Workbooks.OpenText($importcsv, 2, 1, 1, 1, $False, $False, $False, $True)

You need to supply more parameters to the OpenText method to get it to see the delimiter. 您需要向OpenText方法提供更多参数才能使其看到定界符。

$wbpath=Join-Path "$psscriptroot" 'file.xlsx'
$importcsv=Join-Path "$psscriptroot" 'file.txt'
$xl = New-Object -ComObject Excel.Application
$xl.Visible = $true
$xlWindows=2
$xlDelimited=1
$xlTextQualifierDoubleQuote=1
$StartRow=1
$xl.workbooks.OpenText($importcsv,$xlWindows,$StartRow,$xlDelimited,$xlTextQualifierDoubleQuote,$false,$false,$false,$true)
$xl.ActiveWorkbook.SaveAs($wbpath,51)
$xl.Quit()

See the MSDN reference for full details: 有关完整的详细信息,请参见MSDN参考:
https://msdn.microsoft.com/en-us/library/office/ff837097.aspx https://msdn.microsoft.com/zh-CN/library/office/ff837097.aspx
The first $false tells it not to consider consecutive delimiters as one, the next one tells it not to consider Tab as a delimiter, the next $false does the same for semicolon, and the $true tells it to use comma as a delimiter. 第一个$ false告诉它不要将连续的定界符视为一个,第二个$ false告诉它不要将Tab视为定界符,下一个$ false则对分号表示相同,并且$ true告诉它使用逗号作为定界符。 There are additional delimiter options after that that I have not included as the delimiters are all optional, and you only have to include parameters up to the last relevant one to your needs (setting comma to $true). 在此之后,我没有包含其他定界符选项,因为定界符都是可选的,并且您只需要包含直到您需要的最后一个相关参数(将逗号设置为$ true)即可​​。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM