在C#.net中將查詢數(shù)據(jù)導入EXCEL表輸出

字號:

.NET封裝了EXCEL相關的類,以下是實現(xiàn)在程序中標工具條中點擊“EXCEL輸出”按鈕而觸發(fā)的事件,前提是你的系統(tǒng)中裝有EXCEL。
    這是我的代碼,有注釋說明:
    private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
     {//工具條各個按紐單擊事件
     if(e.Button==excelOut)
     {
     Excel.Application excelKccx = new Excel.Application();//創(chuàng)建excel對象
     excelKccx.Workbooks.Add(true);//創(chuàng)建excel工作薄
     DataTable myDataTable=myDataSet.Tables["庫存信息"];//創(chuàng)建一個數(shù)據(jù)表,得到DataSet中“庫存信息”表中的數(shù)據(jù)
     int row=2;
     //把數(shù)據(jù)表的各個信息輸入到excel表中
     for(int i=0;i     {
     excelKccx.Cells[1,i+1]=myDataTable.Columns[i].ColumnName.ToString();
     }
     for(int i=0;i     {
     for(int j=0;j     {
     excelKccx.Cells[row,j+1]=myDataTable.Rows[i][j].ToString();
     }
     row++;
     }
     excelKccx.Visible=true;//使excel可見*/
     }
     else if(e.Button==reportForm)
     {
     //kcRptForm myReport=new kcRptForm();
     //myReport.MdiParent=this;
     //myReport.Show();
     }