PowerShell中将CSV文件转换为EXCEL文件

一直在研究PowerShell,针对CSV文件转换成EXCEL文件(XLSX)一直没找到比较合适方法,查询了许多资料后,整理出来一下这个脚本,目前测试下来速度还不错。

#Define locations and delimiter
$csv = "D:\Test\20210505_042018.csv" #Location of the source file
$xlsx = "D:\Test\20210505_042018.xlsx" #Desired location of output
$delimiter = "," #Specify the delimiter used in the file

# Create a new Excel workbook with one empty sheet
$excel = New-Object -ComObject excel.application 
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$worksheet.Cells.NumberFormat = "@"

# Build the QueryTables.Add command and reformat the data
$TxtConnector = ("TEXT;" + $csv)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = $delimiter
$query.TextFileParseType  = 1
$query.TextFilePlatform = 65001
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1

# Execute & delete the import query
$query.Refresh()
$query.Delete()

# Save & close the Workbook as XLSX.
$Workbook.SaveAs($xlsx,51)
$excel.Quit()

excel2016双击无法打开xlsx文件的解决方法

网上基本提供的方法就是修改注册表的一个地方,可是我的还是不行,后来找到资料还有一个地方,最后将两个地方都修改了,最后成功双击打开文件。

1、打开注册表编辑器“regedit”;
2、定位到如下项目“HKEY_CLASSES_ROOT\Excel.Sheet.12\shell\Open\command”;
3、编辑原有的内容,在最后添加”%1”.
如:原参数为”C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE”
则:新参数为”C:\Program Files (x86)\Microsoft Office\Root\Office16\EXCEL.EXE” “%1”
1、按下win+R后,输入regedit后回车,进入注册表编辑器。
2、在左边的列表里定位到HKEY_Current_User\Software\Microsoft\Office\16.0\excel文件夹
3、把这个excel文件夹直接重命名为excel.old

使用Powershell将多个csv文件转换为多个工作簿的Excel文件

从SQLSERVER数据库通过脚本将数据导出成为CSV文件后,就需要将数据合并为多个工作簿的Excel文件,具体代码如下,大家可以参阅一下。

$path="D:\TestFold" #target folder
cd $path;

$csvs = Get-ChildItem .\* -Include *.csv
$y=$csvs.Count
Write-Host "Detected the following CSV files: ($y)"
foreach ($csv in $csvs)
{
Write-Host "—"$csv.Name
}
$outputfilename = $(get-date -f yyyyMMdd) + "_" + "-data.xlsx" #creates file name with date/username
Write-Host Creating: $outputfilename
$excelapp = new-object -comobject Excel.Application
$excelapp.sheetsInNewWorkbook = $csvs.Count
$xlsx = $excelapp.Workbooks.Add()
$sheet=1

foreach ($csv in $csvs)
{
$row=1
$column=1
$worksheet = $xlsx.Worksheets.Item($sheet)
$worksheet.Name = $csv.Name
$file = (Get-Content $csv)
foreach($line in $file)
{
$linecontents=$line -split ',(?!\s*\w+")'
foreach($cell in $linecontents)
{
$worksheet.Cells.Item($row,$column) = $cell
$column++
}
$column=1
$row++
}
$sheet++
}
$output = $path + "\" + $outputfilename
$xlsx.SaveAs($output)
$excelapp.quit()
cd \ #returns to drive root

Powershell脚本在计划任务中处理产生的Excel文件失败的解决方法

PowerShell脚本在PowerShell ISE中执行一切都正常,但是将脚本加入到Windows的计划任务中就出现无法处理Excel文件的问题,最后在网上找到一个方法,在system32目录下创建Destop目录就可以解决相关问题,遇到这样问题的朋友可以试试。


(32位系统&64位系统)
C:\Windows\System32\config\systemprofile\Desktop

(64位系统)
C:\Windows\SysWOW64\config\systemprofile\Desktop

原文:
Interactive Excel permissions

Stumbled upon an interesting one today, where I had a legacy application that needs to open excel to generate some excel spreadsheets. But when this happened i got the usual error:

System.Runtime.InteropServices.COMException (0x800A03EC): Microsoft Office Excel cannot access the file 'c:\temp\test.xls'. There are several possible reasons:
• The file name or path does not exist.
• The file is being used by another program.
• The workbook you are trying to save has the same name as a currently open workbook.

For this example the application is running under an application pool account called ExcelAppPoolAct

Obviously the first step is to grant the correct permissions in component services. To do this:

  1. Navigation to Adminstrative Tools->Component Services->MyComputer->DCOM->Microsoft Excel Application
  2. Right Click on Microsoft Excel Application and select Properties
  3. Click the Security tab
  4. Change Launch and Activation Permissions to Customize
  5. Click Edit
  6. Add ExcelAppPoolAct
  7. Check Local Launch and Local Activation

Next we need to configure the systemprofile directory. You need to create a Desktop folder in one of the following paths, dependant on which version (32-bit or 64-bit) of Microsoft Office you are running.

Office Version Folder
32-bit C:\Windows\System32\config\ systemprofile\
64-bit C:\Windows\SysWOW64\config\systemprofile\

The next step is to configure the appropriate permissions to thefolders for the Application Pool account, ExcelAppPoolAct. Again the folder is dependent on your version (32-bit or 64-bit) of Microsoft Office.

Folder Required Permission
C:\Windows\System32\config\systemprofile\Desktop Read & Execute, List folder contents, Read
C:\Windows\System32\config\systemprofile\AppData\Roaming\Microsoft Modify, Read & Execute, List Folder Content, Read, Write
C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft Modify, Read & Execute, List Folder Content, Read, Write
Folder Required Permission
C:\Windows\SysWOW64\config\systemprofile\Desktop Read & Execute, List folder contents, Read
C:\Windows\SysWOW64\config\systemprofile\AppData\Roaming\Microsoft Modify, Read & Execute, List Folder Content, Read, Write
C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft Modify, Read & Execute, List Folder Content, Read, Write

I've got a nice piece of powershell that does all of this during installation.

Powershell导出sqlserver数据保存为EXCEL文件并发送邮件脚本

$subject ="邮件主题-$((Get-Date).ToString("yyyyMMdd_hhmmss"))"   
$Database = '数据库名称'
$Server = '数据库地址'
$UserName = '数据库用户名'
$Password = '数据库密码'

#数据库查询脚本
$SqlQuery = "加入SQL查询脚本"
#function Export_Excel {
# Accessing Data Base
$SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object data.dataset
# Filling Dataset
$SqlAdapter.Fill($DataSet)
$DataSetTable = $DataSet.Tables["Table"];

## ———- Working with Excel ———- ##

## – Create an Excel Application instance:
$xlsObj = New-Object -ComObject Excel.Application;

## – Create new Workbook and Sheet (Visible = 1 / 0 not visible)
$xlsObj.Visible = 0;
$xlsWb = $xlsobj.Workbooks.Add();
$xlsSh = $xlsWb.Worksheets.item(1);

## – Build the Excel column heading:
[Array] $getColumnNames = $DataSetTable.Columns | Select ColumnName;

## – Build column header:
[Int] $RowHeader = 1;
foreach ($ColH in $getColumnNames)
{
$xlsSh.Cells.item(1, $RowHeader).font.bold = $true;
$xlsSh.Cells.item(1, $RowHeader) = $ColH.ColumnName;
$RowHeader++;
};

## – Adding the data start in row 2 column 1:
[Int] $rowData = 2;
[Int] $colData = 1;

foreach ($rec in $DataSetTable.Rows)
{
foreach ($Coln in $getColumnNames)
{
## – Next line convert cell to be text only:
$xlsSh.Cells.NumberFormat = "@";

## – Populating columns:
$xlsSh.Cells.Item($rowData, $colData) = $rec.$($Coln.ColumnName).ToString();
$ColData++;
};
$rowData++; $ColData = 1;
};

## – Adjusting columns in the Excel sheet:
$xlsRng = $xlsSH.usedRange;
$xlsRng.EntireColumn.AutoFit();

## ———- Saving file and Terminating Excel Application ———- ##

## – Saving Excel file – if the file exist do delete then save
$xlsFile = "带有路径的文件名_$((Get-Date).ToString("yyyyMMdd_hhmmss")).xls";

if (Test-Path $xlsFile)
{
Remove-Item $xlsFile
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
}
else
{
$xlsObj.ActiveWorkbook.SaveAs($xlsFile);
};

## Quit Excel and Terminate Excel Application process:
$xlsObj.Quit(); (Get-Process Excel*) | foreach ($_) { $_.kill() };

## – End of Script – ##

function SendMail {
#发邮件
$smtpServer = "SMTP服务器地址"
$smtpUser = "SMTP用户名"
$smtpPassword = "SMTP密码"
#$smtp.Send($mail)
$ss=ConvertTo-SecureString -String "$smtpPassword" -AsPlainText -force
$ss|Write-Host
$cre= New-Object System.Management.Automation.PSCredential("$smtpUser",$ss)
Send-MailMessage -to aa@gmail.com,bb@gmail.com -from 发件人显示名称<cc@gmail.com> -Subject $subject -SmtpServer "$smtpServer" -Port 25 -Encoding UTF8 -Attachments $xlsFile  -Credential $cre
}
#Export_Excel
Start-Sleep -Seconds 30
SendMail
echo "remove-item -Force $xlsFile"
remove-item -Force $xlsFile  #删除当前生成的文件

Powershell导出sqlserver数据并发送邮件脚本

用Python创建的邮件服务比较麻烦,后来网上找到可以通过Powershell来连接数据库并导出SQL查询结果为CSV文件,并通过邮箱发送到指定邮箱。

$Date = Get-Date (get-date).AddDays(-1) -uformat "%Y%m%d"
$yDate = Get-Date (get-date).AddDays(-8) -uformat "%Y%m%d"
$fileName = "D:\aa-$Date.csv"
$yfileName = "D:\aa-$yDate.csv"
$Database = '数据库名'
$Server = '192.168.20.33'
$UserName = 'kf'
$Password = '********'
#数据库查询脚本
$SqlQuery = "查询语句"
function Export_Excel {
# Accessing Data Base
$SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$set = New-Object data.dataset
# Filling Dataset
$SqlAdapter.Fill($set)
# Consuming Data
$Table = $Set.Tables[0]
$Table | Export-CSV $fileName
#$Table
}
function SendMail {
#发邮件
$smtpServer = "smtp.163.com"
$smtpUser = "dxlyw_2015"
$smtpPassword = "********"
#$smtp.Send($mail)
$ss=ConvertTo-SecureString -String "$smtpPassword" -AsPlainText -force
$ss|Write-Host
$cre= New-Object System.Management.Automation.PSCredential("$smtpUser",$ss)
Send-MailMessage -to "******@163.com" -from "dxlyw_2015@163.com" -Subject "Call Record" -SmtpServer "$smtpServer" -Credential $cre -Attachments $fileName
}
Export_Excel
Start-Sleep -Seconds 60
SendMail
echo "remove-item -Force $fileName"
remove-item -Force $fileName #删除7天前的文件