- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在不使用 Excel.Application 的情况下在 Powershell 中将 CSV、XLS、XLSM 和 XLSX 之间的文件转换为 CSV、XLS、XLSX 和 XML?我只想使用 MICROSOFT.ACE.OLEDB.12.0。
最佳答案
我先把它写成一个模块,然后更喜欢它作为 ps1 到 .include。
您也可以将它弹出到文件的顶部并在下面调用它。
关于不使用 excel 创建 excel 电子表格的说明:我不太擅长。它似乎正在处理我扔给它的数据。如果您有更好的方法来设置架构并写入文件,我会玩,但我只需要成功,而不是优雅。
''''电源外壳
<#
.SYNOPSIS
This function will take 2 filenames and use the excel application to convert from the first file to the second file.
.DESCRIPTION
This function allows you to use the full power of excel to open and save files. The infile can be any file that excel can open. The outfile can be xlsx, xls or csv. Also, there is an option to delete the destination file before runing the save operation to avoid prompts when overwriting, and to erase the origin file after the process has completed.
.EXAMPLE
Convert-OLEDB -infile 'Source.xls' -outfile 'destination.xlsx' -delete $true
Converts source.xls to xlsx file type.
Deletes source.xls when done.
Deletes destination.xlsx before it converts.
.EXAMPLE
Convert-OLEDB -infile 'Source.xlsx' -outfile 'destination.csv'
Converts xlsx to csv.
Leaves both files behind when done.
.EXAMPLE
Convert-OLEDB -infile 'Source.csv'
Converts infile Source.csv (or whatever format) to xlsx of the same name.
Leaves both behind when done.
.EXAMPLE
Convert-OLEDB -infile 'Source.xlsx' -Extension '.csv'
Converts xlsx to csv. By passing just the extension it will use the same base file name.
Leaves both files behind when done.
.EXAMPLE
dir *.xls | Sort-Object -Property LastWriteTime | Convert-OLEDB -Extension ".csv"
Similar to above but uses the pipeline to do multiple conversions.
If full outfile name is given, it will create just one file over and over again. In this example it would go in chronological order creating csv files.
.EXAMPLE
Dir *.xls | Convert-OLEDB -extension ".csv" -delete $True | Convert-OLEDB -extension ".xls"
That's just weird, but it might solve your problem, and it works.
.PARAMETER infile
Name of the origin file to use. If the full path is not given it will be opened from the context the script is running in.
.PARAMETER outfile (extension)
Name of the destination file to create. If the full path is not given it will save in the default destination of Excel.
.PARAMETER delete
If $true it will delete the target location file if it exists before conversion and the origin file after conversion. Functions like a move with clobber.
If anything else or blank it will leave origin in place and if destination exists it will prompt for overwrite.
#>
function Convert-OLEDB{
param(
[parameter(ValueFromPipeLineByPropertyName=$True,ValueFromPipeline=$True)]
[Alias('FullName')]
[string] $infile,
[Alias('Extension')]
[string] $outfile,
[bool] $delete
)
Begin {
$begin_outfile = $outfile
$oledb = (New-Object system.data.oledb.oledbenumerator).GetElements() | Sort -Property SOURCES_NAME | where {$_.SOURCES_NAME -like "Microsoft.ACE.OLEDB*"} | Select -Last 1
If ($oledb -eq $null) {
Write-Output "MICROSOFT.ACE.OLEDB does not seem to exist on this computer."
Write-Output "Please see https://www.microsoft.com/en-us/download/details.aspx?id=54920"
Write-Output "This can also happen if you have not installed the 32 or 64 bit version "
Write-Output "and you are running this script in the architecture that is missing it."
Write-Output "Solution is to do silent install on missing driver"
break
} else {
$Provider=$Oledb.SOURCES_NAME
Write-Verbose "Provider $Provider found on this computer"
}
}
Process{
#Check infile
if (-not($infile)) {
Write-Output "You must supply a value for -infile"
break
}
else {
Try {
$file = Get-Item $infile
$OleDbConn = New-Object "System.Data.OleDb.OleDbConnection";
$OleDbCmd = New-Object "System.Data.OleDb.OleDbCommand";
$OleDbAdapter = New-Object "System.Data.OleDb.OleDbDataAdapter";
$DataTable = New-Object "System.Data.DataTable";
$Source = $file.FullName
Switch($file.Extension){
".xls" {$OleDbConn.ConnectionString = "Provider=$Provider;Data Source=""$Source"";Extended Properties=""EXCEL 12.0;HDR=Yes;IMEX=1"";"}
".xlsx" {$OleDbConn.ConnectionString = "Provider=$Provider;Data Source=""$Source"";Extended Properties=""EXCEL 12.0 XML;HDR=Yes;IMEX=1"";"}
".xlsm" {$OleDbConn.ConnectionString = "Provider=$Provider;Data Source=""$Source"";Extended Properties=""EXCEL 12.0 MACRO;HDR=Yes;IMEX=1"";"}
Default {
$Source = $file.DirectoryName
$OleDbConn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""$Source"";Extended Properties=""text;HDR=Yes;IMEX=1"";"
}
}
$OleDbCmd.Connection = $OleDbConn;
$OleDbConn.Open();
Switch($file.Extension){
{$_ -in (".xls", ".xlsx",".xlsm")} {$FirstSheet = $OleDbConn.getSchema("Tables")[0].Table_Name}
Default {$FirstSheet = $file.Name}
}
$OleDbCmd.CommandText = "select * from [$FirstSheet];”
$OleDbAdapter.SelectCommand = $OleDbCmd;
$RowsReturned = $OleDbAdapter.Fill($DataTable);
$OleDbConn.Close();
}
Catch {Write-Output "$infile does not seem to exist, or I can't get to it"; break}
}
#Check outfile
#Reset value for pipeline loop
$outfile = $begin_outfile
#If blank just presume xlsx
if (-not($outfile)) {
$outfile = $file.FullName -replace '\.[^.]+$',".xlsx"
Write-Verbose "No outfile supplied, setting outfile to $outfile"
}
#If startswith a dot, use as an extension.
If ($outfile.StartsWith(".")) {
$outfile = $file.FullName -replace '\.[^.]+$',$outfile
Write-Verbose "Extension supplied, setting outfile to $outfile"
}
if ($file.FullName -eq $outfile) {
#Nobody needs us to create a copy of an existing file.
write-verbose "Goal already achieved, moving on"
}
Else {
if(Test-Path ($outfile)){
#Avoid prompting to overwrite by removing an existing file of the same name
Remove-Item -path ($outfile)
}
Try {
#derive XlFileFormat from extension
if($outfile -cmatch '\.[^.]+$') {
$extens="" #Reset for pipeline loop
switch ($Matches[0])
{
".csv" {
#Out to CSV
$DataTable | Export-Csv "$outfile" -NoTypeInformation
}
".xml" {
#Simple, poorly formed:
#$DataTable.TableName = $FirstSheet
#$DataTable.WriteXml("$outfile")
#BetterForm, strongly Typed, empty/Null differentiation
Export-Clixml -Path "$outfile" -InputObject $DataTable
}
Default {
#Out to xlsx
$OleDbConnOut = New-Object "System.Data.OleDb.OleDbConnection";
$OleDbCmdOut = New-Object "System.Data.OleDb.OleDbCommand";
$OleDbAdapterOut = New-Object "System.Data.OleDb.OleDbDataAdapter";
$DataTable2 = New-Object "System.Data.DataTable";
If($Matches[0] -eq ".xls"){$ext_swap = ""}
If($Matches[0] -eq ".xlsx"){$ext_swap = " XML"}
$OleDbConnOut.ConnectionString = "Provider=$Provider;Data Source=""$outfile"";MODE=ReadWrite;Extended Properties=""Excel 12.0$ext_swap"";"
$OleDbCmdOut.Connection = $OleDbConnOut;
$OleDbConnOut.Open();
$Create = "CREATE TABLE [Sheet2] ("
$Stuff = "INSERT INTO [Sheet2] ("
$Stuff2 = "VALUES ("
$DataTable.Columns | % {
$name = $_.ColumnName.Replace("#",".")
$Type = $_.DataType
$Stuff += "[$name], "
$Stuff2 += "?, "
$Create += "[$name] $Type, "
$atname = "@" + $name
}
$Stuff = $Stuff.TrimEnd(", ") + ")"
$Stuff2 = $Stuff2.TrimEnd(", ") + ")"
$Create = $Create.TrimEnd(", ") + ")"
$OleDbCmdOut.CommandText = $Create
$UpdateCount = $OleDbCmdOut.ExecuteNonQuery()
$OleDbAdapterOut.InsertCommand = $Stuff + " " + $Stuff2
$DataTable | % {
$Insert = "INSERT INTO [Sheet2] VALUES ("
$_.ItemArray | % {
$val = $_
$Type = $_.GetType().Name
switch ($Type) {
"Double" {
#Write "$Type"
$Insert += "$val, "
}
"DBNull" {
#Write "$Type"
$Insert += "NULL, "
}
Default {
#Write "$Type"
$val = $val.Replace("""","""""")
$Insert += """$val"", "
}
}
}
$Insert = $Insert.TrimEnd(", ") + ")"
$OleDbCmdOut.CommandText = $Insert
Try {
Write-Verbose "Attempting to run this command: $Insert"
$updatedcount = $OleDbCmdOut.ExecuteNonQuery()
}
Catch{Write-Output "$Error[0] /nIt seems like there was a problem with this command: $Insert"}
}
$OleDbConnOut.Close();
}
}
}
else {
Write-Output "Unable to determine the output file extenstion, this really shouldn''t happen"
break #if it can't find an extension in regex
}
}
Catch {
Write-Host "Unable to convert file $file because powershell with OLEDB cannot open or save it without help"
break
}
if ($delete) {#If asked to delete
if(Test-Path ($outfile)){ #And a file now exists where outfile said it should be
if(Test-Path ($infile)){ #And there is a file at infile
Remove-Item -path ($infile) #Delete it
}
}
}
}
}
End{
#Cleanup
}
}
关于excel - 使用带有 MICROSOFT.ACE.OLEDB.12.0 的 Powershell 在 CSV XML XLS XLSX XLSM 之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58244399/
我准备了一个带有 Visual Basic 代码的 excel 文件。它以 .xlsm 扩展名保存。现在excel图标出现了令人恼火的感叹号。 我可以从图标中删除那个感叹号吗? 最佳答案 使用 .xl
我正在尝试从 xlsm 文件复制宏并将其粘贴到新的 xlsm 文件中。我正在研究 win32com 和 xlwings,但没有找到任何有用的东西。非常感谢解决问题的提示! 最佳答案 安装 Python
我有一个 xlsm 文件,其中已经有很少的数据,需要在自动化过程中写入一些数据并创建一个新的 xlsm 文件。使用以下代码创建文件,但它已损坏且无法打开。文件大小减少,例如从 8kb 到 7kb。不确
当用户打开此工作簿时,我想强制他们立即将文件另存为新文件。对话框打开,但它只会让您将其另存为“所有文件”。 Dim Workbook_Orig As Variant Workbook_Orig
我有三个文件,一个是app.xlsm ,另一个是lib.xlsm , 而 app.xlsm使用 lib.xlsm作为引用(在工具 -> 引用中指定)。第三个,third.xlsm有以下代码: Priv
我有两个 Excel 文件,父文件和子文件,其中子文件包含父函数使用的函数库。出于版本控制的目的,我将它们保存在同一个文件夹中,并在完全相同的位置复制和重命名该文件夹以跟踪我的版本。我还希望动态更新引
亲爱的, 我创建了一个代码来循环遍历文件夹并删除 10 年前的文件,但循环无法正常工作,因为 FolderPath(变量)保持不变并且循环遵循无限循环。有帮助吗? Sub LoopThroughFol
需要帮助才能添加命令以另存为 .xlsm:- Private Sub cmdSaveForm1_Click() Dim strFolder As String Dim i As Lon
我的工作场所内部服务器中有一个 xlsm 文件。假设我们有 2 名 worker 使用此文件,其中包括 2 张,My_sheet和His_sheet . 我正在努力寻找一种方法让我们每个人都可以处理“
所以我正在使用 XLTM 文件,我希望用户确保它们保存为 XLSM。当他们单击“保存”时,效果很好,但我发现当他们单击“另存为”时,文件被保存为“*.xlsm.xlsm”。我对如何确保用户保存为 XL
我正在尝试从用密码加密的 xlsm Excel 文件中读取数据。 到目前为止,我在 Apache POI 网站上找到的方法和堆栈溢出都没有成功 这是我到目前为止所尝试的,以及我得到的异常: S
我有一个非常复杂的 Excel 工作簿,格式为 .xlsm,其中包含宏、命名范围以及所有花里胡哨的东西。我需要将 CSV 文件的内容放入此工作簿中的工作表(已存在)中,从最简单的意义上说:第 1 行第
我正在尝试使用 PHPExcel 读取、克隆和写入 .xlsm 文件,但出现错误: fatal error :未捕获异常“异常”,消息为“工作表!G177 -> 公式错误:发生意外错误”... 任何人
是否可以用 phpexcel 读写带有宏文件的 xlsm? 我测试这段代码只是为了复制原始文件: $objReader = PHPExcel_IOFactory::createReader('Exce
我正在编写的宏有问题。我有我正在编写宏的 xlsm 文件,它正在创建一个模板,该模板从其他人发送给我的多个电子表格中获取数据。但是,我用于信息的一个文件是 xlsm 文件,这给我带来了问题。我相信我已
我想启用我的宏.xlsm文件,只能使用 Excel 打开。 我可以知道并拒绝其他试图打开它的应用程序吗? Private Sub Workbook_Open() ... End Sub 最佳答案 您可
我有一个嵌入的 Word 文档 (*.docm)在我的 Excel 工作表中。 Word 文档包含 table , 与其对应的Table 有关系在 Excel 的 WorkSheet . 我希望在 D
我正在努力将我的 XLSM 转换为 XLSX 文件..它是在转换为 PDF 之前,我试图改变一点但没有成功。 我想与工作簿具有相同的名称,但只是 XLSX 格式。 Sub xlsmtoxlsx() D
我现在使用此代码遇到的主要问题是处理我打开的 xlsm 文件的错误。我对这些文件的 VB 代码没有编辑权限。如果 vb 出错,有没有办法跳过文件? 我有一个包含大约 99 个 xlsm 文件的文件夹,
最奇怪的事情发生在我身上。我有一个 xlsm 工作簿,其中包含各个级别的许多宏(常规、工作表、工作簿)。一切都按预期工作,但如果我尝试从 xlsx 工作簿复制一些单元格并将它们粘贴到我的 xlsm 工
我是一名优秀的程序员,十分优秀!