【问题标题】:Export SQL output to excel sheet将 SQL 输出导出到 Excel 工作表
【发布时间】:2019-04-18 17:49:42
【问题描述】:

我想将 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 的要点......

【问题讨论】:

    标签: sql excel powershell


    【解决方案1】:

    Export-CSV 不会生成 Excel 文件。它会生成一个逗号分隔的文本文件,通常使用 Excel 将其设置为 open。作为 CSV 文件,不知道多个工作表或数据集属性(如工作表名称),因为您需要使用 Excel comobject(及其所有细微差别)。

    这是一个编写真实 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()
    

    您尝试做的事情并不新鲜。互联网上有很多用于此任务的脚本。 Microsoft's Script Center 是查找 powershell 脚本的好地方。 Here is one 似乎可以做你想做的事。

    【讨论】:

      【解决方案2】:

      您可以使用 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"));
              }
          }
      

      Download Source

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多