问题描述
我想将带有互操作性的数据表导出到excel。 我有4列,11行的DataTable。
这是我的全部功能,应该在其中导出数据表:
@H_502_5@static string ExportExcelInterop(DataTable Report,JToken fields) { string fileName = Environment.CurrentDirectory + @"\ExcelRapor.xlsx"; var app = new Microsoft.Office.Interop.Excel.Application(); var workBook = app.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); var sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.ActiveSheet; for (var i = 0; i < Report.Rows.Count; i++) { for (var j = 0; j < Report.Columns.Count; j++) { sheet.Cells[1,j + 1] = Report.Columns[j].ColumnName; sheet.Cells[i + 2,j + 1] = Report.Rows[i][j]; } } Microsoft.Office.Interop.Excel.Range oRange = sheet.Range["A$1:D$11"]; if (app.Application.Sheets.Count < 2) { sheet = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Worksheets.Add(); } else { sheet = app.Worksheets[2]; } sheet.Name = "Pivot Table"; Microsoft.Office.Interop.Excel.Range oRange2 = sheet.Cells[1,1]; Microsoft.Office.Interop.Excel.PivotCache oPivotCache = (Microsoft.Office.Interop.Excel.PivotCache)workBook.PivotCaches().Add(Microsoft.Office.Interop.Excel.XlPivottableSourceType.xlDatabase,oRange); Microsoft.Office.Interop.Excel.Pivottable oPivottable = (Microsoft.Office.Interop.Excel.Pivottable)sheet.Pivottables().Add(PivotCache: oPivotCache,TableDestination: oRange2,TableName: "Pivot Grid"); foreach (var Columns in fields) { string datafield = null; string area = null; string areaIndex = null; string filterValues = null; string filterType = null; foreach (var Key in Columns) { string KeyName = Key.ToString().Substring(0,Key.ToString().IndexOf(':')).Substring(1,Key.ToString().Substring(1,Key.ToString().IndexOf(':')).Length - 2); foreach (var Value in Key) { switch (KeyName) { case "datafield": datafield = Value.ToString(); break; case "area": area = Value.ToString(); break; case "areaIndex": areaIndex = Value.ToString(); break; case "filterValues": filterValues = Value.ToString(); break; case "filterType": filterType = Value.ToString(); break; } } } Microsoft.Office.Interop.Excel.PivotField oPivotField = (Microsoft.Office.Interop.Excel.PivotField)oPivottable.PivotFields(datafield); if (area != null) { if (area == "row") { oPivotField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlRowField; } else if (area == "column") { oPivotField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlColumnField; } else if (area == "data") { oPivotField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xldatafield; } } } workBook.SaveAs(fileName); workBook.Close(); app.Quit(); return fileName; }
我在第三个return foreach上得到异常。 我的例外: @H_502_5@System.Runtime.InteropServices.COMException: 'Pivottable sınıfının PivotFields yöntemi başarısız' 此错误消息翻译为
@H_502_5@PivotFields method of Pivottable class fails
我认为我无法设置正确的@H_502[email protected],因此我的透视图不合适。但是我该如何解决呢?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)