I'm trying to run excel indirect function from c#. I used the following code but got the exception
"A first chance exception of type
'System.Runtime.InteropServices.COMException' occurred in
System.Dynamic.dll"
Additional information: Exception from HRESULT: 0x800A03EC
Excel.Range vehicle_makes_dropdown = xlWorkSheet1.get_Range("B2", "B101");
vehicle_makes_dropdown.Formula = "=indirect(A2)";
vehicle_makes_dropdown.Validation.Add(Excel.XlDVType.xlValidateList, XlDVAlertStyle.xlValidAlertInformation, XlFormatConditionOperator.xlEqual, vehicle_makes_dropdown.Formula, misValue);
vehicle_makes_dropdown.Validation.IgnoreBlank = true;
vehicle_makes_dropdown.Validation.InCellDropdown = true;
Updated Code is
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wlb = app.Workbooks.Open(#"D:\Templates2.xlsx");
Microsoft.Office.Interop.Excel.Worksheet MySheet = (Microsoft.Office.Interop.Excel.Worksheet)wlb.Sheets[1];
Microsoft.Office.Interop.Excel.Range oRange;
// Get Subject
// string subjetcs = string.Empty;
//List<Topics> lstsubject = PickSubject(out subjetcs);
AdminQuestionCommonModel objAdminQuestioncommonModel = new AdminQuestionCommonModel();
// _Question.BindQuestionDropDowns(objAdminQuestioncommonModel);
objAdminQuestioncommonModel.ExcelTopics = _Question.GetTopics(subjectId);
List<SubjectBO> lstTopics = GlobalService.GetAllTopicsandSubtopics(5, subjectId, 0); // get all topics of Subjects
//if (lstsubject.Count > 0)
if (lstTopics.Count > 0)
{
Microsoft.Office.Interop.Excel.Worksheet IDSheet = (Microsoft.Office.Interop.Excel.Worksheet)wlb.Sheets[2];
int rows = 1;
int subrows = 1;
IDSheet.Unprotect("123#");
//foreach (var item in lstsubject)
foreach (var Topic in lstTopics)
{
var TopicName = Topic.Topic_SubTopic.Trim();
TopicName = TopicName.Replace(".", "_").Replace("&", "_").Replace(" ", "_").Replace("__", "_");
// Add the header the first time through
IDSheet.Cells[rows, 1] = Topic.SubjectTopicId.ToString();
IDSheet.Cells[rows, 2] = TopicName;
// List<SubTopics> lst = PickSubTopic(item.TopicName, item.TopicID);
List<SubjectBO> lstsubtopics = _Question.GetSubTopics(subjectId, Topic.SubjectTopicId);
int startindex = subrows;
foreach (var subtopics in lstsubtopics)
{
IDSheet.Cells[subrows, 4] = subtopics.Topic_SubTopic;
IDSheet.Cells[subrows, 5] = subtopics.SubjectTopicId.ToString();
IDSheet.Cells[subrows, 6] = TopicName;
IDSheet.Cells[subrows, 7] = Topic.SubjectTopicId.ToString();
subrows++;
}
if (lstTopics.Count > 0)
{
wlb.Names.Add(TopicName, IDSheet.get_Range("D" + startindex + ":D" + (subrows - 1)));
}
subrows++;
rows++;
}
wlb.Names.Add("Topics", IDSheet.get_Range("B1:B" + (rows - 1)));
Microsoft.Office.Interop.Excel.Range Range = MySheet.get_Range("B2", "B800");
Range.Validation.Delete();
Range.NumberFormat = "Text";
//Range.Cells.Value = lstsubject[0].TopicName.ToString();
Range.Cells.Value = "Text";
Range.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertStop
, Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween
, Formula1: "=Topics"
);
Range.Validation.InCellDropdown = true;
Range.Validation.IgnoreBlank = true;
oRange = MySheet.get_Range("c2","c3");
oRange.Validation.Delete();
oRange.NumberFormat = "Text";
oRange.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList, Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertStop
, Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween
, Formula1: "=INDIRECT(B2)"
);
oRange.Validation.InCellDropdown = true;
oRange.Validation.IgnoreBlank = true;
IDSheet.Protect("123#");
//Range.Validation.InCellDropdown = true;
//Range.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(255, 217, 217, 0));
app.Visible = true;
}
You need to put double quotes around your cell reference inside the formula:
vehicle_makes_dropdown.Formula = "=indirect(""A2"")";
oRange.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList,
Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertStop,
Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween,
Formula1: "=INDIRECT(if(B2=\"\",A5000,B2))"
// see also http://user.qzone.qq.com/26149705/blog/1474296940
Related
I am trying to create a winform that will search an Excel sheet to find matching text values. When the value is found, I need to continue searching for any more values that are the same. After, the results are placed in a ListView.
Currently, my program is finding all matching values in each row, but it is finding the same row several times before moving onto the next.
Any help would be appreciated.
This is a snippet of the search code:
var app = new Microsoft.Office.Interop.Excel.Application();
var workbook = app.Workbooks.Open(#"//FilePath//");
var sheet = workbook.Worksheets["sheet1"];
Microsoft.Office.Interop.Excel.Range currentFind = null;
Microsoft.Office.Interop.Excel.Range firstFind = null;
object missing = System.Reflection.Missing.Value;
var range = (Microsoft.Office.Interop.Excel.Range)sheet.Columns["A:F"];
currentFind = range.Find(All, missing, Microsoft.Office.Interop.Excel.XlFindLookIn.xlValues,
Microsoft.Office.Interop.Excel.XlLookAt.xlPart, Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows,
Microsoft.Office.Interop.Excel.XlSearchDirection.xlNext, false, missing, missing);
var address = currentFind.Address;
while (currentFind != null)
{
if (firstFind == null)
{
firstFind = currentFind;
}
else if (currentFind.Address[Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1] ==
firstFind.Address[Microsoft.Office.Interop.Excel.XlReferenceStyle.xlA1])
{
break;
}
var row = currentFind.EntireRow;
object[,] rowvalues = row.Value2;
var column = currentFind.EntireColumn;
object[,] colvalues = column.Value2;
string[] arr = new string[6];
ListViewItem itm;
arr[0] = Convert.ToString(rowvalues[1, 1]);
arr[1] = Convert.ToString(rowvalues[1, 2]);
arr[2] = Convert.ToString(rowvalues[1, 3]);
arr[3] = Convert.ToString(rowvalues[1, 4]);
arr[4] = Convert.ToString(rowvalues[1, 5]);
arr[5] = Convert.ToString(rowvalues[1, 6]);
itm = new ListViewItem(arr);
listView1.Items.Add(itm);
currentFind = range.FindNext(currentFind);
}
I create a pivot table based on an Excel (.xlsx) file. The program adds fields to rows, values, and the filter. Using PivotFilters.Add2 causes 0x800a03ec error which terminates the program. How to properly use PivotFilters.Add2?
I tried filtering on different fields with different data types. Also, I tried using Type.Missing in a place of unused arguments. There seems to be plenty of information of this method for VB, but not so much for C#.
Items selected in the filter should be between the two dates on the last line.
var xlApp = new Microsoft.Office.Interop.Excel.Application();
xlApp.Visible = true;
var workBook = xlApp.Workbooks.Open(spreadsheetLocation);
var workSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets["Data"];
var workSheet2 = (Microsoft.Office.Interop.Excel.Worksheet)workBook.Sheets.Add();
Microsoft.Office.Interop.Excel.Range last = workSheet1.Cells.SpecialCells(Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Microsoft.Office.Interop.Excel.Range range = workSheet1.get_Range("A1", last);
Microsoft.Office.Interop.Excel.PivotCaches pivotCaches = null;
Microsoft.Office.Interop.Excel.PivotCache pivotCache = null;
Microsoft.Office.Interop.Excel.PivotTable pivotTable = null;
Microsoft.Office.Interop.Excel.PivotFields pivotFields = null;
Microsoft.Office.Interop.Excel.PivotField filterField = null;
Microsoft.Office.Interop.Excel.PivotField accNumField = null;
Microsoft.Office.Interop.Excel.PivotField amountPaidField = null;
pivotCaches = workBook.PivotCaches();
pivotCache = pivotCaches.Create(XlPivotTableSourceType.xlDatabase, range);
pivotTable = pivotCache.CreatePivotTable(workSheet2.Cells[1,1]);
pivotFields = (Microsoft.Office.Interop.Excel.PivotFields)pivotTable.PivotFields();
amountPaidField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AmountPaid");
amountPaidField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlDataField;
amountPaidField.NumberFormat = "$#,###,###.00";
accNumField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AccNumber");
accNumField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlRowField;
filterField = (Microsoft.Office.Interop.Excel.PivotField)pivotFields.Item("AccDate");
filterField.Orientation = Microsoft.Office.Interop.Excel.XlPivotFieldOrientation.xlPageField;
filterField.EnableMultiplePageItems = true;
filterField.PivotFilters.Add2(XlPivotFilterType.xlDateBetween, Type.Missing, DateTime.Now.AddDays(-30), DateTime.Now.AddDays(-20));
#First it deletes two rows and then it creates a pivot table#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;
namespace ConsoleApplication4
{
class Program
{
public static string Column(int column)
{
column--;
if (column >= 0 && column < 26)
return ((char)('A' + column)).ToString();
else if (column > 25)
return Column(column / 26) + Column(column % 26 + 1);
else
throw new Exception("Invalid Column #" + (column + 1).ToString());
}
static void Main(string[] args)
{
try
{
string path = #"C:\Users\UX155512\Documents\Book1fd.xlsx";
var excelFile = new Application();
Workbook workBook = excelFile.Workbooks.Open(path);
Worksheet workSheet = workBook.Worksheets[1];
Worksheet pivotSheet = workBook.Worksheets.Add(
System.Reflection.Missing.Value,
workBook.Worksheets[workBook.Worksheets.Count],
1,
System.Reflection.Missing.Value);
Range last = workSheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);
int lastRow = last.Row;
int lastCol = last.Column;
string lastColVal = Column(lastCol);
string lastFilledCol = lastColVal + lastRow.ToString();
Console.WriteLine(lastFilledCol);
Console.WriteLine(lastColVal);
Console.WriteLine(lastRow);
Console.WriteLine(lastCol);
for (int i = 1; i <= lastRow; i++)
{
if (workSheet.Cells[1][i].Value == ("HDR"))
{
workSheet.Rows[i].Delete();
Console.WriteLine("The Row Containing HDR has been deleted");
}
if (workSheet.Cells[1][i].Value == ("TRL"))
{
workSheet.Rows[i].Delete();
Console.WriteLine("The Row Containing TLR has been deleted");
}
}
Range lastRange = workSheet.Range["A1", lastFilledCol];
pivotSheet.Name = "Pivot Table";
Range range = pivotSheet.Cells[1, 1];
PivotCache pivotCache = (PivotCache)workBook.PivotCaches().Add(XlPivotTableSourceType.xlDatabase, lastRange);
PivotTable pivotTable = (PivotTable)pivotSheet.PivotTables().Add(PivotCache: pivotCache, TableDestination: range);
PivotField pivotField = (PivotField)pivotTable.PivotFields("Plan Number");
pivotField.Orientation = XlPivotFieldOrientation.xlRowField;
PivotField pivotField2 = (PivotField)pivotTable.PivotFields("Source");
pivotField2.Orientation = XlPivotFieldOrientation.xlColumnField;
PivotField pivotField3 = (PivotField)pivotTable.PivotFields("Total");
pivotField3.Orientation = XlPivotFieldOrientation.xlDataField;
pivotField3.Function = XlConsolidationFunction.xlSum;
workBook.SaveAs(#"C:\Users\UX155512\Documents\Excel Dump\Trial9.xlsx");
workBook.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.Read();
}
}
}
As mentioned above by Asger, the filter can't be added to a page field. Instead, the pivot item's visibility property has to be set.
var pivotItems = filterField.PivotItems();
DateTime date = Convert.ToDateTime(item.Name);
foreach (var item in pivotItems)
{
item.Visible = false;
if (date < DateTime.Now.AddDays(-30) || date > DateTime.Now.AddDays(-20))
{
item.Visible = true;
}
}
The best way to find the answer to pretty much ANY interop question is to record a macro then examine the source.
I'm trying to create two charts on a pivot table. When I create the first one it's ok, but when I try to create the second one I'm getting this following error: "HRESULT E_FAIL has been returned from a call to a COM component"
chartPage.SetSourceData(oPivotTable.TableRange2, misValue);
Follow below the code to you guys understand what I'm doing
Workbook xlWorkBook = xlApp.Workbooks.Add (rootFile + "Template.xlsm");
Worksheet xlWorkSheet = (Worksheet) xlWorkBook.Worksheets.get_Item (1);
if (!Directory.Exists (rootFile)) {
Directory.CreateDirectory (rootFile);
}
string fileName = rootFile + report.Name + ".xlsm";
xlWorkSheet.Name = "Invoices";
List<Sheet> sheets = JsonConvert.DeserializeObject<List<Sheet>> (report.Definition);
var startCell = (Range) xlWorkSheet.Cells[1, 1];
var endCell = (Range) xlWorkSheet.Cells[invoices.Count () + creditNotes.Count (), properties.Count () + 1];
var writeRange = xlWorkSheet.Range[startCell, endCell];
writeRange.Value = dataSource;
int lastROW = xlWorkSheet.Cells[xlWorkSheet.Rows.Count, 1].End (XlDirection.xlUp).Row;
int LastCol = xlWorkSheet.Cells[1, xlWorkSheet.Columns.Count].End (XlDirection.xlToLeft).Column;
Range pRange = xlWorkSheet.Cells[1, 1].Resize (lastROW, LastCol);
pRange.Columns.AutoFit ();
foreach (var sheet in sheets) {
PivotCache oPivotCache = (PivotCache) xlWorkBook.PivotCaches ().Add (XlPivotTableSourceType.xlDatabase, pRange);
xlWorkBook.ShowPivotChartActiveFields = true;
Worksheet xlWorkSheetPivot = (Worksheet) xlWorkBook.Worksheets.Add (misValue);
xlWorkSheetPivot.Name = sheet.tabHeading;
xlWorkSheetPivot.Activate ();
foreach (Pivot pivot in sheet.pivots) {
Range last = GetRange (xlWorkSheetPivot);
PivotTable oPivotTable = (PivotTable) xlWorkSheetPivot.PivotTables ().Add (PivotCache: oPivotCache, TableDestination: last, TableName: pivot.title);
oPivotTable.SortUsingCustomLists = false;
foreach (var filter in pivot.filters) {
PivotField oPivotFieldrow1 = (PivotField) oPivotTable.PivotFields (filter.displayName);
oPivotFieldrow1.EnableMultiplePageItems = true;
oPivotFieldrow1.Orientation = XlPivotFieldOrientation.xlPageField;
oPivotFieldrow1.Name = filter.displayName;
if (!String.IsNullOrEmpty (filter.value)) {
oPivotFieldrow1.CurrentPage = filter.value;
}
}
foreach (var row in pivot.rows) {
PivotField oPivotFieldrow1 = (PivotField) oPivotTable.PivotFields (row.displayName);
oPivotFieldrow1.Orientation = XlPivotFieldOrientation.xlRowField;
oPivotFieldrow1.LayoutCompactRow = true;
oPivotFieldrow1.LayoutForm = XlLayoutFormType.xlOutline;
oPivotFieldrow1.Name = row.displayName;
}
foreach (var column in pivot.columns) {
PivotField oPivotFieldrow1 = (PivotField) oPivotTable.PivotFields (column.displayName);
oPivotFieldrow1.Orientation = XlPivotFieldOrientation.xlColumnField;
oPivotFieldrow1.LayoutCompactRow = true;
oPivotFieldrow1.LayoutForm = XlLayoutFormType.xlOutline;
oPivotFieldrow1.Name = column.displayName;
}
var functionToOrder = "";
foreach (var value in pivot.values) {
PivotField field = (PivotField) oPivotTable.PivotFields (value.displayName);
field.Orientation = XlPivotFieldOrientation.xlDataField;
field.NumberFormat = "0.00";
if (value.function != null)
field.Function = GetEnumExcel (value.function.name);
field.Caption = System.Text.RegularExpressions.Regex.Replace (field.Caption, #"[\d-]", string.Empty);
field.Name = System.Text.RegularExpressions.Regex.Replace (field.Name, #"[\d-]", string.Empty);
functionToOrder = field.Name;
}
if (pivot.pivotType == "Chart") {
ChartObjects xlCharts = (ChartObjects) xlWorkSheetPivot.ChartObjects (Type.Missing);
ChartObject myChart = (ChartObject) xlCharts.Add (oPivotTable.TableRange2.Left + 350, last.Top, 400, 200);
Chart chartPage = myChart.Chart;
chartPage.SetSourceData (oPivotTable.TableRange2, misValue);
chartPage.ChartType = (XlChartType) pivot.chartType.id;
}
if (pivot.values.Count > 1) {
oPivotTable.DataPivotField.Orientation = XlPivotFieldOrientation.xlColumnField;
}
//Order By Fields
if (pivot.fieldToOrder != null && pivot.orderType != 0 && (!string.IsNullOrEmpty (pivot.fieldToOrder.displayName) || pivot.fieldToOrder.function != null)) {
PivotField pivotField = oPivotTable.PivotFields (pivot.fieldToOrder.displayName);
var fieldToOrder = pivot.fieldToOrder.function == null ? pivot.fieldToOrder.displayName : pivot.fieldToOrder.function.name + " of " + pivot.fieldToOrder.displayName;
xlApp.Run ("UseOrderFunction", sheet.tabHeading, pivot.title, pivot.rows.FirstOrDefault ().displayName, pivot.orderType, fieldToOrder);
}
oPivotTable.RowAxisLayout (XlLayoutRowType.xlTabularRow);
if (pivot.topCount.HasValue && pivot.topCount > 0) {
var fieldToUseTop = pivot.fieldToOrder.function == null ? functionToOrder : pivot.fieldToOrder.function.name + " of " + pivot.fieldToOrder.displayName;
xlApp.Run ("UseTopFunction", sheet.tabHeading, pivot.title, pivot.rows.FirstOrDefault ().displayName, pivot.topCount, pivot.orderType, fieldToUseTop);
}
}
}
I expect this below works:
if (pivot.pivotType == "Chart") {
ChartObjects xlCharts = (ChartObjects) xlWorkSheetPivot.ChartObjects (Type.Missing);
ChartObject myChart = (ChartObject) xlCharts.Add (oPivotTable.TableRange2.Left + 350, last.Top, 400, 200);
Chart chartPage = myChart.Chart;
chartPage.SetSourceData (oPivotTable.TableRange2, misValue);
chartPage.ChartType = (XlChartType) pivot.chartType.id;
}
public static void GenerateExcel()
{
string conString = #"Server=DESKTOP-QVPUIDU\SQLEXPRESS; Database=Erasmus_Students;Integrated Security = SSPI;";
StringBuilder query = new StringBuilder();
query.Append("select * from ErasmusStudent");
SQL.DataTable dtProducts = new SQL.DataTable();
using (SqlConnection cn = new SqlConnection(conString))
{
using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
{
da.Fill(dtProducts);
}
}
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Application oXL;
oXL = new Application();
oWB = oXL.Workbooks.Add(Missing.Value);
oSheet = (_Worksheet)oWB.ActiveSheet;
oSheet = (_Worksheet)oXL.Worksheets.Add();
oSheet.Name = "Erasmus";
try
{
SQL.DataTable dtCategories = dtProducts.DefaultView.ToTable(true, "FirstName");
foreach (SQL.DataRow category in dtCategories.Rows)
{
string[] colNames = new string[dtProducts.Columns.Count];
int col = 0;
foreach (SQL.DataColumn dc in dtProducts.Columns)
colNames[col++] = dc.ColumnName;
string lastColumn = "A";
if (dtProducts.Columns.Count > 25)
lastColumn += (char)(65 + dtProducts.Columns.Count - 1);
else
lastColumn = Convert.ToString((char)(65 + dtProducts.Columns.Count - 1));
oSheet.get_Range("A1", lastColumn + "1").Value2 = colNames;
oSheet.get_Range("A1", lastColumn + "1").Font.Bold = true;
oSheet.get_Range("A1", lastColumn + "1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter;
SQL.DataRow[] dr = dtProducts.Select(string.Format("FirstName='{0}'", category[0].ToString()));
string[,] rowData = new string[dr.Count<SQL.DataRow>(), dtProducts.Columns.Count];
int rowCnt = 0;
int redRows = 2;
foreach (SQL.DataRow row in dr)
{
for (col = 0; col < dtProducts.Columns.Count; col++)
{
rowData[rowCnt, col] = row[col].ToString();
}
/*if (int.Parse(row["ReorderLevel"].ToString()) < int.Parse(row["UnitsOnOrder"].ToString()))
{
Range range = oSheet.get_Range("A" + redRows.ToString(), "J" + redRows.ToString());
range.Cells.Interior.Color = System.Drawing.Color.Red;
} */
redRows++;
rowCnt++;
}
oSheet.get_Range("A2", lastColumn + rowCnt.ToString()).Value2 = rowData;
}
oXL.DisplayAlerts = false;
oWB.SaveAs("Erasmus.xlsx");
oWB.Close(0);
oXL.Quit();
SendEmail();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Marshal.ReleaseComObject(oSheet);
Marshal.ReleaseComObject(oWB);
Marshal.ReleaseComObject(oXL);
}
}
So the problem is that every time i run the build one process of excel doesn't close i finished my day with 30-40 open processes and now i realized this.
I tried to close the file with quit and close and also i tried to release it with Marshal i'm out of ideas at the moment.
Any suggestion/code improvement is welcome.
Open processes
I might be far from having an answer but the last time I saw this kind of behavior, it was the computer antivirus blocking everything. Maybe try disabling it and run your app?
Also, maybe this can help? I can't kill MyApp.vshost.exe
i am using Interop.Excel to export data from datatable and generate line chart too. i have got a code which export data to excel from data table and also create chart there but the code is giving error at this line
Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
Excel.XlAxisGroup.xlPrimary);
and the error message i am getting Value does not fall within the expected range
my full code for line chart generation.
private void button1_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = GetGraphData();
Excel.Application xla = new Excel.Application();
xla.Visible = true;
Excel.Workbook wb = xla.Workbooks.Add(Excel.XlSheetType.xlWorksheet);
Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;
//********************** Now create the chart. *****************************
Excel.ChartObjects chartObjs = (Excel.ChartObjects)ws.ChartObjects(Type.Missing);
Excel.ChartObject chartObj = chartObjs.Add(250, 60, 300, 300);
Excel.Chart xlChart = chartObj.Chart;
int nRows = 2;
int nColumns = dt.Rows.Count;
string upperLeftCell = "B2";
int endRowNumber = System.Int32.Parse(upperLeftCell.Substring(1))
+ nRows - 1;
char endColumnLetter = System.Convert.ToChar(
Convert.ToInt32(upperLeftCell[0]) + nColumns - 1);
string upperRightCell = System.String.Format("{0}{1}",
endColumnLetter, System.Int32.Parse(upperLeftCell.Substring(1)));
string lowerRightCell = System.String.Format("{0}{1}",
endColumnLetter, endRowNumber);
Excel.Range rg = ws.get_Range(upperLeftCell, lowerRightCell);
for (int i = 1; i <= dt.Rows.Count; i++)
{
rg[1, i] = dt.Rows[i - 1][0].ToString(); //For Adding Header Text
rg[2, i] = int.Parse(dt.Rows[i - 1][1].ToString()); //For Adding Datarow Value
}
Excel.Range chartRange = ws.get_Range(upperLeftCell, lowerRightCell);
xlChart.SetSourceData(chartRange, Type.Missing);
xlChart.ChartType = Excel.XlChartType.xlLine;
// *******************Customize axes: ***********************
Excel.Axis xAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlCategory,
Excel.XlAxisGroup.xlPrimary);
//xAxis.HasTitle = true;
// xAxis.AxisTitle.Text = "X Axis";
Excel.Axis yAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlSeriesAxis,
Excel.XlAxisGroup.xlPrimary);
//yAxis.HasTitle = true;
//yAxis.AxisTitle.Text = "Y Axis";
Excel.Axis zAxis = (Excel.Axis)xlChart.Axes(Excel.XlAxisType.xlValue,
Excel.XlAxisGroup.xlPrimary);
//zAxis.HasTitle = true;
//zAxis.AxisTitle.Text = "Z Axis";
// *********************Add title: *******************************
xlChart.HasTitle = true;
xlChart.ChartTitle.Text = "Project Status Graph";
// *****************Set legend:***************************
xlChart.HasLegend = true;
FileStream file = new FileStream(#"c:\pop.xls", FileMode.Create);
file.Close();
wb.SaveCopyAs(#"c:\pop.xls");
// ****************For Quiting The Excel Aplication ***********************
if (xla != null)
{
xla.DisplayAlerts = false;
wb.Close();
wb = null;
xla.Quit();
xla = null;
}
}
private System.Data.DataTable GetGraphData()
{
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.AddRange(new DataColumn[2] { new DataColumn("ProjectStatus"), new DataColumn("per") });
DataRow dr1 = dt.NewRow();
dr1[0] = "Compleet";
dr1[1] = 20;
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2[0] = "Pending";
dr2[1] = 20;
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3[0] = "UnCompleet";
dr3[1] = 20;
dt.Rows.Add(dr3);
return dt;
}
looking for help. thanks
My coworker tells me that according to intellisense, the value of the first argument (Excel.XlAxisType.xlSeriesAxis) is valid only for 3D charts.
What kind of chart are you creating?