using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelFunkcjeStatystyczne
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Excel.Application xlApp;
            const int iloscRzutow = 10;

            try
            {
                xlApp = (Excel.Application)System.Runtime.InteropServices.
                    Marshal.GetActiveObject("Excel.Application");
            }
            catch
            {
                xlApp = new Excel.Application();
            }

            xlApp.Visible = true;

            if (xlApp.Workbooks.Count == 0)
                xlApp.Workbooks.Add();

            Excel.Worksheet ws = xlApp.ActiveSheet;            
            Random r = new Random();

            for (int i = 1; i <= iloscRzutow; i++)
            {
                // Pierwsza kostka
                ws.Cells[i, 1].Value2 = 1 + r.Next(5);
                // Druga kostka
                ws.Cells[i, 2].Value2 = 1 + r.Next(5);
                // Suma oczek
                ws.Cells[i, 3].Value2 = 
                    ws.Cells[i, 1].Value2 + ws.Cells[i, 2].Value2;
            }

            // Sumy
            ws.Cells[iloscRzutow + 1, 1].Value2 = 
                "=SUM(A1:A" + iloscRzutow.ToString() + ")";
            ws.Cells[iloscRzutow + 1, 2].Value2 = 
                "=SUM(B1:B" + iloscRzutow.ToString() + ")";
            ws.Cells[iloscRzutow + 1, 3].Value2 = 
                "=SUM(C1:C" + iloscRzutow.ToString() + ")";

            // Wartości średnie
            ws.Cells[iloscRzutow + 2, 1].Value2 = 
                "=AVERAGE(A1:A" + iloscRzutow.ToString() + ")";
            ws.Cells[iloscRzutow + 2, 2].Value2 = 
                "=AVERAGE(B1:B" + iloscRzutow.ToString() + ")";
            ws.Cells[iloscRzutow + 2, 3].Value2 = 
                "=AVERAGE(C1:C" + iloscRzutow.ToString() + ")";

            Excel.Font font;
            // Formatowanie komórek zawierających sumy
            font = ws.get_Range("A" + (iloscRzutow + 1).ToString(), 
                "C" + (iloscRzutow + 1).ToString()).Font;
            font.Bold = true;
            font.Size = 14;

            // Formatowanie komórek zawierających średnie
            font = ws.get_Range("A" + (iloscRzutow + 2).ToString(), 
                "C" + (iloscRzutow + 2).ToString()).Font;
            font.Italic = true;
            font.Size = 16;
        }
    }
}
