應用ExcelPackage導出Excel


前陣子工作需要,要實現從數據庫中導出數據到Excel。老套路 先去百度上查閱資料,發現了以下幾種方法:

1:將DataGrid控件中的數據導出Excel

2:將dataview導出excel

3:從網頁上用html繪制Excel 表格  等。。

總體上感覺比較繁瑣 比如用dataview導出excel時, Excel表格的格式需要在程序中設置,不利於后期的修改維護。而ExcelPackage的優勢就是解放了在程序中設置格式的弊端,總體原理為:在相應路徑下放置一個Excel模板,執行導出操作時按照模板樣式在指定行插入數據,構建出一個模板樣式的新Excel。

 

excelpackage的官網:http://excelpackage.codeplex.com/ ,里面有所需的.dll文件和demo程序。

 

接下來是我應用Excelpackage導出Excel的小程序,就當拋磚引玉了~      代碼如下:

 

 

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using OfficeOpenXml;

namespace twins
{
     public  partial  class _Default : System.Web.UI.Page
    {
         protected  void Page_Load( object sender, EventArgs e)
        {

        }

         protected  void btnExcel_Click( object sender, EventArgs e)
        {
             //  DataTable dt = getData().Tables[0];
            FileInfo newFile =  new FileInfo(Server.MapPath( " ~/new.xls ")); //生成的Excel,放在根目錄下了
             string path = Server.MapPath( " ~/template.xls ");   //模板Excel,放在根目錄下
            FileInfo template =  new FileInfo(path);
             if (!template.Exists)
                throw  new Exception( " Template file does not exist! ");
             using (ExcelPackage xlPackage =  new ExcelPackage(newFile, template))
            {
                 //  uncomment this line if you want the XML written out to the outputDir
                
// xlPackage.DebugMode = true; 

                
//  get handle to the existing worksheet
                ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets[ " student "];  //Excel的sheet1位置
                 if (worksheet !=  null)
                {
                    ExcelCell cell;
                     const  int startRow =  3;           //開始插入數據的數據行,自行設置
                     int row = startRow;

                     using (SqlDataReader sqlReader = getReader())
                    {
                         //  get the data and fill rows 5 onwards
                         while (sqlReader.Read())
                        {
                             int col =  1;
                             //  we have our total formula on row 7, so push them down so we can insert more data
                             if (row > startRow) worksheet.InsertRow(row);

                             //  our query has the columns in the right order, so simply
                            
//  iterate through the columns
                             for ( int i =  0; i < sqlReader.FieldCount; i++)
                            {
                                 //  use the email address as a hyperlink for column 1
                                 if (sqlReader.GetName(i) ==  " EmailAddress ")
                                {
                                     //  insert the email address as a hyperlink for the name
                                     string hyperlink =  " mailto: " + sqlReader.GetValue(i).ToString();
                                    worksheet.Cell(row,  1).Hyperlink =  new Uri(hyperlink, UriKind.Absolute);
                                }
                                 else
                                {
                                     //  do not bother filling cell with blank data (also useful if we have a formula in a cell)
                                     if (sqlReader.GetValue(i) !=  null)
                                        worksheet.Cell(row, col).Value = sqlReader.GetValue(i).ToString();
                                    col++;
                                }
                            }
                            row++;
                        }

                        sqlReader.Close();

                         //  delete the two spare rows we have in the template
                        worksheet.DeleteRow(row,  true);
                        worksheet.DeleteRow(row,  true);
                        row--;
                    }
                    //用於設置excel表的格式
                     for ( int iCol =  1; iCol <=  5; iCol++)               
                    {
                        cell = worksheet.Cell(startRow, iCol);
                         for ( int iRow = startRow; iRow <= row; iRow++)
                        {
                            worksheet.Cell(iRow, iCol).StyleID = cell.StyleID;
                        }
                    }
                
                }
        

                 //  save the new spreadsheet
                 try
                {
                    xlPackage.Save();  //保存生成的Excel
                }
                 catch(Exception e3){
                    
                }
                
            }
        }

         protected SqlDataReader getReader()
        {
             const  string connStr =  " server=.;database =oz;Integrated Security =true ";
            SqlConnection mySqlConnection =  new SqlConnection(connStr); // 新建連接對象  
             string sqlStr =  "  select name,sex,tel,email,job from student "; // SQL語句  
            mySqlConnection.Open(); // 打開連接  
            SqlCommand common =  new SqlCommand(sqlStr, mySqlConnection);
            SqlDataReader sdr = common.ExecuteReader();
             return sdr;
           
        }
    }
}

在根目錄下放置一個template.xls文件--用於模板。我的模板如下圖所示:

 

 運行程序,會把數據庫student表中數據插入到excel中,我本機的student表如下圖所示:

 

之后在根目錄下會看到生成一個新Excel文件-new.xls. 迫不及待的打開,看到如下圖 所示:

 

 成功!!!

 值得注意的是:

1:執行程序之后,template.xls是不會變的(它只是一個模板),改變的只有新生成的new.xls

2:new.xls 1,2行中靜態的標題和標頭的樣式和模板是一致的,而動態的數據樣式可以在模板excel中設置。在我此程序設置的方法為:在模板的第三行,右擊鼠標->設置單元格格式->對齊居中,字體華文行楷。 設置后生成的excel中就能出現上圖所示的效果,是不是很方便吶~

3: 經測試,2步驟的設置貌似只能在Excel2007中生效,也就是說如果在excel2003中設置字體和居中都是無效的!我也沒有辦法,同學們可以自己試一試 如果可以的話告訴我一聲啊。

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM