之乎者也,阿弥陀佛

软件设计的原则就是,化繁为简,化难为易,把人的思维集中在简单的领域,然后通过有序的组合实现复杂的逻辑。

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

string saveFileName = @"e:\xx.xls";
   List<ExcelInfo>list=daochuInfo.selExcel();//数据源
   if (list.Count==0)
       return;
   bool fileSaved=false;
   Excel.Application xlApp=new Excel.Application();
   if(xlApp==null)
   {
       this.Page.RegisterStartupScript("script", "<script>alert('无法创建Excel对象,可能您的机子未安装Excel');</script>");
       return;
   }
   Excel.Workbooks workbooks=xlApp.Workbooks;
   Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
   Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
   //写入字段
    worksheet.Cells[1,1]="B";
    worksheet.Cells[1, 2] = "C";
    worksheet.Cells[1, 3] = "D";
   //写入数值
  
   for(int r=0;r<list.Count;r++)
   {
       ExcelInfo excelInfo = (ExcelInfo)list[r];
     worksheet.Cells[r+2,1]=excelInfo.B;
     worksheet.Cells[r + 2, 2] = excelInfo.C;
     worksheet.Cells[r + 2,3] = excelInfo.D;
   }
   worksheet.Columns.EntireColumn.AutoFit();//列宽自适应。
   if(saveFileName!="")
   {
    try
    {
     workbook.Saved =true;
     workbook.SaveCopyAs(saveFileName);
     fileSaved=true;
    }
    catch(Exception ex)
    {
     fileSaved=false;
     this.Page.RegisterStartupScript("script", "<script>alert('导出文件时出错,文件可能正被打开!');</script>");
    }
   }
   else
   {
    fileSaved=false;
   }
   xlApp.Quit();
   GC.Collect();//强行销毁
    }

 public static List<ExcelInfo> selExcel()
    {
        string str = "select b,c,d from tb_excel";
        using (SqlConnection sqlCon = new SqlConnection(Database.conStr))
        {
            using (SqlCommand sqlCmd = new SqlCommand(str, sqlCon))
            {
                sqlCon.Open();
                List<ExcelInfo> list = new List<ExcelInfo>();
                SqlDataReader dr = sqlCmd.ExecuteReader();
                while (dr.Read())
                {
                    ExcelInfo excelInfo = new ExcelInfo();
                    excelInfo.B = dr[0].ToString();
                    excelInfo.C = dr[1].ToString();
                    excelInfo.D = dr[2].ToString();
                    list.Add(excelInfo);
                }
                return list;
            }
        }
    }

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ak_ljd/archive/2009/04/28/4134687.aspx

posted on 2009-07-13 13:41  搏击的小船  阅读(4096)  评论(0编辑  收藏  举报