我希望将sql输出输出到excel文件,以及我给它命名的工作表,即不是"Sheet1“。我怎么才能开始编码呢?
下面是读取sql输出的当前代码。
$sql_output = @()
while ($rdr.read()){
$sql_output += [PSCustomObject][Ordered]@{
Col1=$rdr.GetValue(0)
Col2=$rdr.GetValue(1)
Col3=$rdr.GetValue(2)
Col4=$rdr.GetValue(3)
Col5=$rdr.GetValue(4)
}
$count=$count + 1
}
然后出口到csv
$sql_output | Export-CSV "D:\Script\Network_Threat_Protection.csv" -NoTypeInfo -Append
我最终希望这个powershell脚本读取多个sql查询,并将其输出到excel中的不同工作表,但让我先将导出到excel的jist .
发布于 2014-08-06 17:43:35
Export-CSV
不生成Excel文件。它生成一个逗号分隔的文本文件,通常设置为使用Excel打开。作为一个CSV文件,您不了解多个工作表或数据集属性(如sheetnames ),因为您需要使用Excel (及其所有细微之处)。
下面是一个编写实际Excel文件的基本示例:
$a = New-Object -com Excel.Application
$a.Visible = $True
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Cells.Item(1,1) = "A value in cell A1."
$b.SaveAs("C:\Scripts\Test.xls")
$a.Quit()
你想做的事并不新鲜。在互联网上有很多脚本来完成这项任务。微软脚本中心是找到powershell脚本的好地方。这里有一个似乎能做你想做的事。
发布于 2019-04-18 09:49:42
可以使用CPPLUS库将表导出到excel工作表。
private DataTable GetData(string tableName)
{
using (SqlConnection sqlCon = new SqlConnection(connectionString))
{
SqlCommand sqlCommand = new SqlCommand("SELECT * FROM " + tableName, sqlCon);
sqlCon.Open();
var reader = sqlCommand.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
}
private void SaveExcel(DataTable dataTable, string newFile)
{
using (ExcelPackage pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(newFile);
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
pck.SaveAs( new System.IO.FileInfo("d:\\Export\\" + newFile + ".xlsx"));
}
}
https://stackoverflow.com/questions/25166576
复制相似问题