使用C#和Excel进行报表开发(三)-生成统计图(Chart)4

private   void  button4_Click( object  sender, EventArgs e)
{
    
try
    
{
        ThisApplication 
= new Excel.Application();
        m_objBooks 
= (Excel.Workbooks)ThisApplication.Workbooks;
        ThisWorkbook 
= (Excel._Workbook)(m_objBooks.Add(Type.Missing));

        ThisApplication.DisplayAlerts 
= false;

        
this.DeleteSheet();
        
this.AddDatasheet();
        
this.LoadData();

        CreateChart();

        ThisWorkbook.SaveAs(
"z:\\Book2.xls", Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    }

    
catch (Exception ex)
    
{
        MessageBox.Show(ex.Message);
    }

    
finally
    
{
        ThisWorkbook.Close(Type.Missing, Type.Missing, Type.Missing);
        ThisApplication.Workbooks.Close();

        ThisApplication.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisWorkbook);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(ThisApplication);
        ThisWorkbook 
= null;
        ThisApplication 
= null;
        GC.Collect();
        
this.Close();
    }


}


Excel.Application ThisApplication 
=   null ;
Excel.Workbooks m_objBooks 
=   null ;
Excel._Workbook ThisWorkbook 
=   null ;

Excel.Worksheet xlSheet 
=   null ;

/**/ /// <summary>
/// 用生成的随机数作数据
/// </summary>

private   void  LoadData()
{
    Random ran 
= new Random();
    
for (int i = 1; i <= 12; i++)
    
{
        xlSheet.Cells[i,  
1= i.ToString() + "";
        xlSheet.Cells[i, 
2= ran.Next(2000).ToString();    
    }

}

/**/ /// <summary>
/// 删除多余的Sheet
/// </summary>

private   void  DeleteSheet()
{
    
foreach (Excel.Worksheet ws in ThisWorkbook.Worksheets)
        
if (ws != ThisApplication.ActiveSheet)
        
{
            ws.Delete();
        }

    
foreach (Excel.Chart cht in ThisWorkbook.Charts)
        cht.Delete();
            
}

/**/ /// <summary>
/// 创建一个Sheet,用来存数据
/// </summary>

private   void  AddDatasheet()
{
    xlSheet 
= (Excel.Worksheet)ThisWorkbook.
        Worksheets.Add(Type.Missing, ThisWorkbook.ActiveSheet,
        Type.Missing, Type.Missing);

    xlSheet.Name 
= "数据";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值