无法创建数据透视表

时间:2018-07-07 14:33:58

标签: c# excel pivot

我正在尝试使用C#创建一个Excel Pivot表。我正在使用Microsoft.Office.Interop.Excel。尽管其他一切正常,但涉及到此行

Excel.PivotCache pivotCache = (Excel.PivotCache)wkb.PivotCaches()

没有添加选项来添加数据源,但是大多数在线资源告诉我有一个添加选项。如何添加数据源?

编辑:请注意,此处使用的Excel实际上正在使用 Excel = Microsoft.Office.Interop.Excel;问题仍然没有答案。

1 个答案:

答案 0 :(得分:1)

您需要使用添加来获取单个数据透视缓存对象。这是一个示例:

void Main()
{
    Excel.Application xl = new Excel.Application();
    var wb = xl.Workbooks.Add();
    var pc = wb.PivotCaches().Add(XlPivotTableSourceType.xlExternal);

    pc.Connection = @"OLEDB;Provider=SQLNCLI11.0;server=.\SQLExpress2012;Database=Northwind;Trusted_connection=yes";
    pc.CommandType = XlCmdType.xlCmdSql;
    pc.CommandText = @"Select c.CustomerID, c.CompanyName, 
  o.orderId, o.orderDate, 
  e.FirstName+(' '+e.LastName) As Employee, 
  p.ProductName,
  od.UnitPrice, od.Quantity
  FROM  Customers c 
  INNER Join Orders o
  ON o.CustomerID = c.CustomerID
  INNER Join Employees e 
  ON e.EmployeeID = o.EmployeeID
  INNER Join [Order Details] od
  ON od.OrderID = o.OrderID 
  INNER Join products p 
  ON p.ProductID = od.ProductID
  order By p.ProductName";

  var ws = (Excel.Worksheet)wb.ActiveSheet;
    pc.CreatePivotTable(ws.Range["A1"], "myPivot");
    var pt = (Excel.PivotTable)ws.PivotTables("myPivot");

    pt.AddFields(new string[] {"ProductName"}, new string[] {"Employee"});
    var pvf = (Excel.PivotField)pt.PivotFields("Quantity");
    pvf.Orientation = XlPivotFieldOrientation.xlDataField;
    xl.Visible=true;
}