根据“ group by”子句自动分离Excel工作表

时间:2019-03-28 17:22:09

标签: excel powershell

我需要将.csv文件导入Excel(我已经使用SQLCMD和Powershell进行了组合,这在下面显示,尽管它是我的实际列/文件的精简版本),但是为了为了减少行数(我有数百万个数据记录),现在我想根据一个SQL group by子句将数据拆分到同一工作簿中的单独工作表中(每个“ Group”将是它自己的工作表)。 / p>

这是我的SQLCMD代码:

SQLCMD -s"," -S servername -U username -d databasename -W -o 
"mydatafile.csv” -Q "SET NOCOUNT ON 
SELECT Account, QUOTENAME(cast ([ColDescription] as nvarchar(100)),'""') as 
ColumnDescription" FROM myTable

我的powershell代码:

### Set input and output path
$inputCSV = "C:\Users\username\Desktop\LSGTransactions.CSV"
$outputXLSX = "C:\Users\username\Desktop\Book1.XLSX"

### 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)

### Build the QueryTables.Add command
### QueryTables does the same as when clicking "Data » From Text" in Excel
$TxtConnector = ("TEXT;" + $inputCSV)
$Connector = 
$worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)

### Set the delimiter (, or ;) according to your regional settings
$query.TextFileOtherDelimiter = $Excel.Application.International(5)

### Set the format to delimited and text for every column
### A trick to create an array of 2s is used with the preceding comma
$query.TextFileParseType  = 1
$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. Change the output extension for Excel 
2003
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()

我相信我可以弄清楚如何在excel书中创建新工作表,但是我正在尝试集思广益,以检测何时创建新工作表...我可以在powershell中实现循环机制吗?

否...也许我需要找到一种方法来将我的带组的SQL语句导出到多个.csv文件中,然后使用powershell脚本将所有.csv文档导入到一个excel工作簿中(尝试使用现在)。

0 个答案:

没有答案