[英]Excel VSTO + C# .NET + Create Pivot Table
我正在嘗試通過 C# .Net 為 Excel VSTO 創建一個數據透視表,但不斷拋出一個異常,指出:
HRESULT 異常:0x800A03EC
我正在嘗試創建數據透視表的工作表稱為 oSheet 並且與具有源數據的工作表相同
我為數據透視表源創建了一個范圍:
Excel.Range pivotData = osheet.Range["A1", "B3"];
數據透視表所在的范圍:
Excel.Range pivotDest = osheet.Range["A12", "B14"];
然后嘗試用這個創建表:
osheet.PivotTableWizard(
Excel.XlPivotTableSourceType.xlDatabase,
pivotData,
pivotDest,
"Table",
true,
true,
true,
true,
true,
true,
false,
false,
Excel.XlOrder.xlDownThenOver,
0,
false,
false
);
錯誤發生在表向導行中。
關於導致錯誤的原因或通過 C# .Net 創建數據透視表的更好方法的任何想法?
完整代碼
Excel.Application oApp;
Excel.Worksheet osheet;
Excel.Workbook oBook;
oApp = new Excel.Application();
oBook = oApp.Workbooks.Add();
osheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
osheet.Cells[1, 1] = "Name";
osheet.Cells[1, 2] = "Salary";
osheet.Cells[2, 1] = "Frank";
osheet.Cells[2, 2] = 1500000;
osheet.Cells[3, 1] = "Millford";
osheet.Cells[3, 2] = 2200;
//Now capture range of first sheet = I will need this to create pivot table
Excel.Range oRange = osheet.Range["A1", "B3"];
var pch = oBook.PivotCaches();
Excel.Range pivotData = osheet.Range["A1", "B3"];
Excel.PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, pivotData);
Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable");
pvt.PivotFields("Col1").Orientation = XlPivotFieldOrientation.xlRowField;
pvt.PivotFields("Col2").Orientation = XlPivotFieldOrientation.xlColumnField;
pvt.AddDataField(pvt.PivotFields("Col3"), "Sum of Col3", XlConsolidationFunction.xlSum);
前幾天剛回答了一個類似的問題...
https://stackoverflow.com/a/39968355/1278553
簡而言之,在 C# 中創建數據透視表的方法是:
Excel.Range pivotData = osheet.Range["A1", "B3"];
Excel.PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, pivotData);
Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable");
然后分配您的行/列和數據字段:
pvt.PivotFields("Col1").Orientation = XlPivotFieldOrientation.xlRowField;
pvt.PivotFields("Col2").Orientation = XlPivotFieldOrientation.xlColumnField;
pvt.AddDataField(pvt.PivotFields("Col3"), "Sum of Col3", XlConsolidationFunction.xlSum);
我從我之前的答案中大量抄襲。
-- 編輯 10/17/2016 --
根據您更新的代碼,現在應該可以創建數據透視表:
var pch = oBook.PivotCaches();
Excel.Range pivotData = osheet.Range["A1", "B3"];
Excel.PivotCache pc = pch.Create(Excel.XlPivotTableSourceType.xlDatabase, pivotData);
Excel.PivotTable pvt = pc.CreatePivotTable(osheet.Range["A12"], "MyPivotTable");
pvt.PivotFields("Name").Orientation = Excel.XlPivotFieldOrientation.xlRowField;
pvt.AddDataField(pvt.PivotFields("Salary"), "Total Salary",
Excel.XlConsolidationFunction.xlSum);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.