Reputation: 331
I have a quick question. I have this c# program that i want to store data into an excel chart. So far i have managed to store the values into five different columns. Each column stands for one kind of calculation: time acceleration velocity force distance (in that order). I want to create an excel time-distance chart using c#. I have no idea where to start. Here is my excel creator method: Any help will be greatly appreciated. Thank you.
public void exportResults()
{
Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
Console.WriteLine("Excel is not properly installed!!");
return;
}
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i;
int j;
for (j = 0; j < 5; j++)
{
xlWorkSheet.Cells[1, 1] = "Time";
xlWorkSheet.Cells[1, 2] = "Acceleration";
xlWorkSheet.Cells[1, 3] = "Velocity";
xlWorkSheet.Cells[1, 4] = "Force";
xlWorkSheet.Cells[1, 5] = "Distance";
}
// set each cell
for(i = 0; i <= 30; i++){
for (j = 0; j < 5; j++)
{
xlWorkSheet.Cells[i+2, j+1] = data[i, j];
}
}
xlWorkBook.SaveAs(/*"c:\\csharp-Excel.xls"*/ Directory.GetCurrentDirectory(), Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);
Console.WriteLine("Excel file created , you can find it in the directory you stored it: {0}", Directory.GetCurrentDirectory());
}
Upvotes: 1
Views: 190
Reputation: 1336
Add the following after creating your cells.
// Add a using statement
// using Excel = Microsoft.Office.Interop.Excel;
Excel.Range chartRange;
Excel.ChartObjects xlCharts = (Excel.ChartObjects)xlWorkSheet.ChartObjects(Type.Missing);
Excel.ChartObject myChart = (Excel.ChartObject)xlCharts.Add(10, 80, 300, 250);
Excel.Chart chartPage = myChart.Chart;
chartRange = xlWorkSheet.get_Range("A1", "C12"); // your data grid range
chartPage.SetSourceData(chartRange, misValue);
chartPage.ChartType = Excel.XlChartType.xlConeCol;//xlCylinderCol;//xlLine;//xlColumnClustered;
//export chart as picture file
chartPage.Export(@"H:\img\excel_chart_export.png", "PNG", misValue);
You can change the type of chart at the line stating.
chartPage.ChartType = Excel.XlChartType
Upvotes: 1