//创建一个excel application
   Excel.Application xls_exp=null;  
   int rowindex=1;
   int colindex=0;
          //创建一个workbook,一个worksheet
   Excel._Workbook xls_book=null;
   Excel._Worksheet xls_sheet=null;
   try
   {
       xls_exp=new Excel.ApplicationClass();
       xls_book=xls_exp.Workbooks.Add(true);
        xls_sheet=(Excel._Worksheet)xls_book.ActiveSheet;
         //取得数据
       DataTable aa=GetData();
       //将所得到的表的列名,赋值给单元格
       foreach(DataColumn col in aa.Columns)
        {
             colindex++;
       xls_exp.Cells[1,colindex]=col.ColumnName;
                   //水平对齐
       xls_sheet.get_Range(xls_exp.Cells[1,colindex],xls_exp.Cells[1,colindex]).HorizontalAlignment=Excel.XlVAlign.xlVAlignCenter;
         //垂直对齐
        xls_sheet.get_Range(xls_exp.Cells[1,colindex],xls_exp.Cells[1,colindex]).VerticalAlignment=Excel.XlVAlign.xlVAlignCenter;
                 //行高、列宽自适应
       //xls_sheet.Cells.Rows.AutoFill();
       //xls_sheet.Cells.Columns.AutoFill();
        }
       //同样方法处理数据
       foreach(DataRow row in aa.Rows)
        {
               rowindex++;
       colindex=0;      
         foreach(DataColumn col in aa.Columns)
           {
            colindex++;
            switch (row[col.ColumnName].GetType().ToString())
            {
              //字符
               case ("System.String"):
                             //数字格式设置为文本
                 xls_sheet.get_Range(xls_exp.Cells[rowindex,colindex],xls_exp.Cells[rowindex,colindex]).NumberFormatLocal="@";
                              //水平对齐
                 xls_sheet.get_Range(xls_exp.Cells[rowindex,colindex],xls_exp.Cells[rowindex,colindex]).HorizontalAlignment=Excel.XlVAlign.xlVAlignCenter;
                                                        //垂直对齐
                 xls_sheet.get_Range(xls_exp.Cells[rowindex,colindex],xls_exp.Cells[rowindex,colindex]).VerticalAlignment=Excel.XlVAlign.xlVAlignCenter;
                 break;
               //日期
               case("System.DateTime"):
                            //数字格式设置为yyyy-mm-dd hh:mm:ss日期
                 xls_sheet.get_Range(xls_exp.Cells[rowindex,colindex],xls_exp.Cells[rowindex,colindex]).NumberFormatLocal="YYYY-MM-DD HH:MM:SS";
                 break;
            }
                         //给cell赋值
            xls_exp.Cells[rowindex,colindex]=row[col.ColumnName];
                    
           }
         }
       //不可见,即后台处理
       xls_exp.Visible=true;
   catch(Exception err)
   {
    MessageBox.show(err.Message);
   }
   //finally
   //{
    //xls_exp.Quit();
   //}
      
posted on 2007-12-23 15:30  shf  阅读(3259)  评论(0编辑  收藏  举报