2013-10-24 4 views
0

Я использую Interop.Excel для экспорта данных из datatable и создания линейной диаграммы.Как создать диаграмму строк из datatable C# winform

я мог бы успешно экспортировать данные, чтобы преуспеть из данных, как таким образом

public static bool Export(System.Data.DataTable dt, string sheetName) 
{ 
    object Missing = System.Reflection.Missing.Value; 
    Excel.Application oXL; 
    Excel.Workbook oWB; 
    Excel.Worksheet oSheet; 
    Excel.Range oRange; 

    try 
    { 
     // Start Excel and get Application object. 
     oXL = new Excel.Application(); 

     // Set some properties 
     oXL.Visible = false; 
     oXL.DisplayAlerts = false; 

     // Get a new workbook. 
     oWB = oXL.Workbooks.Add(Missing); 

     // Get the Active sheet 
     oSheet = (Excel.Worksheet)oWB.ActiveSheet; 
     oSheet.Name = sheetName; 

     oSheet.Cells[1, 1] = "Daily Finished Job History " + DateTime.Now.ToString("dd/MM/yyyy"); 

     oSheet.get_Range("A1", "A1").ColumnWidth = 13; 
     oSheet.get_Range("B1", "B1").ColumnWidth = 13; 
     oSheet.get_Range("C1", "C1").ColumnWidth = 25; 
     oSheet.get_Range("A1", "C1").Font.Size = 14; 

     oSheet.get_Range("A1", "C1").Font.Bold = true; 
     oSheet.get_Range("A1", "C1").Merge(true); 
     oSheet.get_Range("A1", "C1").Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; 

     oSheet.get_Range("A3", "C3").Font.Bold = true; 

     int rowCount = 3; 
     for (int i = 1; i < dt.Columns.Count + 1; i++) 
     { 
      oSheet.Cells[rowCount, i] = dt.Columns[i - 1].ColumnName; 
     } 

     foreach (DataRow dr in dt.Rows) 
     { 
      rowCount += 1; 
      for (int i = 1; i < dt.Columns.Count + 1; i++) 
      { 
       oSheet.Cells[rowCount, i] = dr[i - 1].ToString(); 
      } 
     } 

     // Resize the columns 
     oRange = oSheet.get_Range(oSheet.Cells[1, 1], 
     oSheet.Cells[rowCount, dt.Columns.Count]); 
     //oRange.EntireColumn.AutoFit(); 

     // Save the sheet and close 
     oSheet = null; 
     oRange = null; 

     string strParentDirectory = GetParentDirectory(); 
     strParentDirectory = strParentDirectory + "\\Data"; 
     if (!Directory.Exists(strParentDirectory)) 
     { 
      Directory.CreateDirectory(strParentDirectory); 
     } 
     string strFileName = strParentDirectory + "\\DailyFinishedJobHistory_" + DateTime.Now.ToString("yyyyMMdd") + ".xls"; 
     if (File.Exists(strFileName)) 
     { 
      File.Delete(strFileName); 
     } 
     FileStream file = new FileStream(strFileName, FileMode.Create); 
     file.Close(); 

     oWB.SaveAs(strFileName, Excel.XlFileFormat.xlWorkbookNormal, 
      Missing, Missing, Missing, Missing, 
      Excel.XlSaveAsAccessMode.xlExclusive, 
      Missing, Missing, Missing, 
      Missing, Missing); 
     oWB.Close(Missing, Missing, Missing); 
     oWB = null; 
     oXL.Quit(); 
    } 
    catch 
    { 
     throw; 
    } 
    finally 
    { 
     // Clean up 
     // NOTE: When in release mode, this does the trick 
     GC.WaitForPendingFinalizers(); 
     GC.Collect(); 
     GC.WaitForPendingFinalizers(); 
     GC.Collect(); 
    } 

    return true; 
} 

public static string GetParentDirectory() 
{ 
    System.IO.DirectoryInfo myDirectory = new DirectoryInfo(Environment.CurrentDirectory); 
    return myDirectory.Parent.Parent.FullName; 
} 

Теперь я хочу, чтобы генерировать диаграмму в одном листе, на основании данных моей DataTable.

My Excel файл будет выглядеть следующим образом enter image description here

я прочитал НЕМНОГУЮ статье & кода для создания диаграммы из этого ссылки http://www.dotnetbull.com/2011/09/exporting-pie-chart-into-excel-file.html http://csharp.net-informations.com/excel/csharp-excel-chart.htm http://www.daniweb.com/software-development/csharp/threads/80834/c-and-excel-chart-ranges

, но до сих пор не в состоянии понять код генерировать линейную диаграмму. было бы очень полезно, если бы кто-нибудь помог мне создать диаграмму на одном листе, как показано здесь.

благодаря

ответ

0

Попробуйте это в качестве отправной точки:

'Create & Format Chart 
Dim oChart As Excel.Chart 

oChart = oXL.Parent.Charts.Add 
With oChart 
    .Name = "History" 
    .HasTitle = True 
    .ChartTitle.Font.ColorIndex = 11 
    .ChartTitle.Font.Bold = True 
    .ChartTitle.Font.Size = 12 
    .ChartTitle.Font.Name = "Arial" 
    .ChartTitle.Text = "Job History" 
    .ChartType = Excel.XlChartType.xlLine 
    .HasLegend = True 
    .SeriesCollection(1).XValues = "=Sheet1!$A$4:$A$6" 
    .SeriesCollection(1).Name = "=Sheet1!$B$3" 
    .SeriesCollection(2).Name = "=Sheet1!$C$3" 
    .SeriesCollection(3).Name = "=Sheet1!$D$3" 
End With 
Смежные вопросы