C#從List匯出到EXCEL

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.