asp.net匯出excel資料的常見方法匯總_實用技巧

來源:互聯網
上載者:User

本文執行個體講述了asp.net中一些常用的excel資料匯出方法,同時也介紹了在資料匯入或匯出時可能碰到的一些問題總結,分享給大家供大家參考。希望文章對你會有所協助。具體實現方法如下:

1、由dataset產生

複製代碼 代碼如下:
public void CreateExcel(DataSet ds,string typeid,string FileName) 
  {
   HttpResponse resp;
   resp = Page.Response;
   resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
   resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);   
   string colHeaders= "", ls_item="";
   int i=0;
 
   //定義表對象與行對像,同時用DataSet對其值進行初始化
   DataTable dt=ds.Tables[0];
   DataRow[] myRow=dt.Select(""); 
   // typeid=="1"時匯出為EXCEL格式檔案;typeid=="2"時匯出為XML格式檔案
   if(typeid=="1")
   {
    //取得資料表各欄位標題,各標題之間以t分割,最後一個欄位標題後加斷行符號符
    for(i=0;i     colHeaders+=dt.Columns[i].Caption.ToString()+"t";
    colHeaders +=dt.Columns[i].Caption.ToString() +"n";   
    //向HTTP輸出資料流中寫入取得的資料資訊
    resp.Write(colHeaders); 
    //逐行處理資料  
    foreach(DataRow row in myRow)
    {
     //在當前行中,逐列獲得資料,資料之間以t分割,結束時加斷行符號符n
     for(i=0;i      ls_item +=row[i].ToString() + "t";     
     ls_item += row[i].ToString() +"n";
     //當前行資料寫入HTTP輸出資料流,並且置空ls_item以便下行資料    
     resp.Write(ls_item);
     ls_item="";
    }
   }
   else
   {
    if(typeid=="2")
    { 
     //從DataSet中直接匯出XML資料並且寫到HTTP輸出資料流中
     resp.Write(ds.GetXml());
    }    
   }
   //寫緩衝區中的資料到HTTP標頭檔中
   resp.End();
}

2、由datagrid產生

複製代碼 代碼如下:
public void ToExcel(System.Web.UI.Control ctl)  
  {
   HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
   HttpContext.Current.Response.Charset ="UTF-8";    
   HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
   HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
   ctl.Page.EnableViewState =false;   
   System.IO.StringWriter  tw = new System.IO.StringWriter() ;
   System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
   ctl.RenderControl(hw);
   HttpContext.Current.Response.Write(tw.ToString());
   HttpContext.Current.Response.End();
  }

 
用法:ToExcel(datagrid1); 
 
3、這個用dataview

複製代碼 代碼如下:
public void OutputExcel(DataView dv,string str)
{
   //
   // TODO: 在此處添加建構函式邏輯
   //
   //dv為要輸出到Excel的資料,str為標題名稱
   GC.Collect();
   Application excel;// = new Application();
   int rowIndex=4;
   int colIndex=1;
 
   _Workbook xBk;
   _Worksheet xSt;
 
   excel= new ApplicationClass();
  
   xBk = excel.Workbooks.Add(true);
   
   xSt = (_Worksheet)xBk.ActiveSheet;
 
   //
   //取得標題
   //
   foreach(DataColumn col in dv.Table.Columns)
   {
    colIndex++;
    excel.Cells[4,colIndex] = col.ColumnName;
    xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[4,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設定標題格式為置中對齊
   }
 
   //
   //取得表格中的資料
   //
   foreach(DataRowView row in dv)
   {
    rowIndex ++;
    colIndex = 1;
    foreach(DataColumn col in dv.Table.Columns)
    {
     colIndex ++;
     if(col.DataType == System.Type.GetType("System.DateTime"))
     {
      excel.Cells[rowIndex,colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設定日期型的欄位格式為置中對齊
     }
     else
      if(col.DataType == System.Type.GetType("System.String"))
     {
      excel.Cells[rowIndex,colIndex] = "'"+row[col.ColumnName].ToString();
      xSt.get_Range(excel.Cells[rowIndex,colIndex],excel.Cells[rowIndex,colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter;//設定字元型的欄位格式為置中對齊
     }
     else
     {
      excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
     }
    }
   }
   //
   //載入一個合計行
   //
   int rowSum = rowIndex + 1;
   int colSum = 2;
   excel.Cells[rowSum,2] = "合計";
   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,2]).HorizontalAlignment = XlHAlign.xlHAlignCenter;
   //
   //設定選中的部分的顏色
   //
   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Select();
   xSt.get_Range(excel.Cells[rowSum,colSum],excel.Cells[rowSum,colIndex]).Interior.ColorIndex = 19;//設定為淺黃色,共計有56種
   //
   //取得整個報表的標題
   //
   excel.Cells[2,2] = str;
   //
   //設定整個報表的標題格式
   //
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Bold = true;
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,2]).Font.Size = 22;
   //
   //設定報表表格為最適應寬度
   //
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Select();
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Columns.AutoFit();
   //
   //設定整個報表的標題為跨列置中
   //
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).Select();
   xSt.get_Range(excel.Cells[2,2],excel.Cells[2,colIndex]).HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
   //
   //繪製邊框
   //
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,colIndex]).Borders.LineStyle = 1;
   xSt.get_Range(excel.Cells[4,2],excel.Cells[rowSum,2]).Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//設定左邊線加粗
   xSt.get_Range(excel.Cells[4,2],excel.Cells[4,colIndex]).Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//設定上邊線加粗
   xSt.get_Range(excel.Cells[4,colIndex],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//設定右邊線加粗
   xSt.get_Range(excel.Cells[rowSum,2],excel.Cells[rowSum,colIndex]).Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//設定下邊線加粗
   //
   //顯示效果
   //
   excel.Visible=true;
 
   //xSt.Export(Server.MapPath(".")+"\"+this.xlfile.Text+".xls",SheetExportActionEnum.ssExportActionNone,Microsoft.Office.Interop.OWC.SheetExportFormat.ssExportHTML);
   xBk.SaveCopyAs(Server.MapPath(".")+"\"+this.xlfile.Text+".xls");
 
   ds = null;
            xBk.Close(false, null,null);
   
            excel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);
            xBk = null;
            excel = null;
   xSt = null;
            GC.Collect();
   string path = Server.MapPath(this.xlfile.Text+".xls");
 
   System.IO.FileInfo file = new System.IO.FileInfo(path);
   Response.Clear();
   Response.Charset="GB2312";
   Response.ContentEncoding=System.Text.Encoding.UTF8;
   // 添加頭資訊,為"檔案下載/另存新檔"對話方塊指定預設檔案名稱
   Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
   // 添加頭資訊,指定檔案大小,讓瀏覽器能夠顯示下載進度
   Response.AddHeader("Content-Length", file.Length.ToString());
   
   // 指定返回的是一個不能被用戶端讀取的流,必須被下載
   Response.ContentType = "application/ms-excel";
   
   // 把檔案流發送到用戶端
   Response.WriteFile(file.FullName);
   // 停止頁面的執行
  
   Response.End();
}
 
 
匯入、匯出EXCEL中的一些問題匯總

一、在項目中的添加引用:
  右擊項目資源管理員的引用-->添加引用-->選擇.NET選項卡-->選擇Microsoft.Office.Interop.Excel-->確定;
 
  在選擇時注意一下.NET組件的版本號碼,本例的12.0.0.0是Office2007的版本:
二、在項目中使用Microsoft.Office.Interop.Excel:
      如果想使用Microsoft.Office.Interop.Excel,首先需要在項目中引用命名空間:
  using Microsoft.Office.Interop.Excel;
三、建立Excel.Application相關對象
       

複製代碼 代碼如下:
//建立Application對象
        Microsoft.Office.Interop.Excel.Application myExcel = new Application();
  //建立Workbooks對象
         Workbooks myBooks = myExcel.Application.Workbooks;
     //建立一個System.Reflection.Missing的object對象
        object oMissing = System.Reflection.Missing.Value;

四、開啟或建立Excel的book檔案
  
複製代碼 代碼如下:
//開啟Excel檔案,注意裡的“ExccelFilePath”為Excel檔案在伺服器上的物理地址,包括檔案名稱
  Workbook myBook = myBooks.Open(ExccelFilePath,oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
     //建立Workseet對象,,此處為要操作的工作表 ,當前要操作的工作表的擷取方法有兩種:使用工作表的索引值或使用工作表的名稱,名稱預設為:“sheet1”/“Sheet2”等
     Worksheet mySheet = (Worksheet)myBook.Worksheets[1];
    //如果是建立EXCEL活頁簿,需要 設定如下兩行內容,以保證活頁簿中有一個工作表,
    Workbook workbook1 = excel1.Workbooks.Add(true);
    Worksheet mySheet= (Worksheet)workbook1.Worksheets["sheet1"];
    //設定EXCEL對象是否顯示介面,預設為false不顯示介面
    myExcel.Visble=true;

五、一些比較重要的針對Excel的操作
     1、擷取Range對象
   ①、擷取一個儲存格的Range對象:
    

複製代碼 代碼如下:
//選擇第一行、第一列的單元的儲存格為Range對象
            Range r = (Excel.Range)mySheet.Cells[1, 1];
          //選擇多個連續的儲存格為Range對象
   Range r=(Excel.Range)Range.get_Range("A1:F3")

        ②、給儲存格賦值或取出儲存格的值:
        
複製代碼 代碼如下:
//已選擇了Range對象的賦值:
   r.Text="中國";
       //未選擇Range對象的賦值:
        mySheet.Cells[1,2].Text="中國";
     //已選擇了Range對象的取值:
   String strValue= r.Text;
       //未選擇Range對象的取值:
    String  strValue=  mySheet.Cells[1,2].Text;

     ③、給儲存格設定邊框
        
複製代碼 代碼如下:
mySheet.Cells[2, 1].BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null);//畫線

     ④、合併儲存格
  
複製代碼 代碼如下:
//合併儲存格前先要將要合并的儲存格選擇為Range對象
            Range r=Range.get_Range("A1:F3");
  //然後現設定合併儲存格
         r.MergeCells = true;

     ⑤、設定儲存格的字型、字型大小、背景色等屬性
    
複製代碼 代碼如下:
mySheet.Cells[1, 1].Font.Name = "黑體";
        mySheet.Cells[1, 1].Font.Size = 20;
        mySheet.Rows["1:1"].RowHeight = 40;
    mySheet.Cells[1, 1].Interior.Color = Color.FromArgb(224, 224, 224);//設定顏色

   ⑥、刪除一行:
   
複製代碼 代碼如下:
//首先擷取要刪除的行的Range
    Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)mySheet.Rows[sendedRow[1], Type.Missing];
   //注意刪除行後刪除後的行號被下面的行替換,如果逐行刪除,請先從最大的行號往最小的行號刪除
       range.Delete(Microsoft.Office.Interop.Excel.XlDeleteShiftDirection.xlShiftUp);

  ⑦、擷取有資料的行數
   
複製代碼 代碼如下:
int rowsint = mySheet.UsedRange.Cells.Rows.Count;

六、EXCEL檔案的儲存與退出

1、EXCEL的儲存與退出
  

複製代碼 代碼如下:
myBook.Save();
   myBooks.Close();
   myExcel.Quit();

2、EXCEL指定檔案儲存
   

複製代碼 代碼如下:
myBook.Close(true, FilePath +_file_Name, null);

七、釋放EXCLE對象的資源與結束EXCEL  進程
   關於這方面內容有好多網友都在講多種方法,經過本人實踐,以下方面才能真正做到結束EXCEL的任務進程:
1、將所有以上對EXCEL的操作放到一個方法中,
2、在操作EXCEL後,即時將不使用對象一一釋放並賦null值:
  
複製代碼 代碼如下:
System.Runtime.InteropServices.Marshal.ReleaseComObject(mysheet);
  mysheet=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myBook);
  myBook=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myBooks);
  myBooks=null;
  System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
  myExcel=null;

3、再建立一個方法,並以該方法中執行上面建立的操作EXCEL方法,並在執行完操作EXCEL方法的後面添加GC.Collect():
複製代碼 代碼如下:
//下面方法中OutPutEXCEL()方法是輸出EXCEL檔案的對EXCEL 操作的方法
private void killExcel()
{
  outPutEXCEL();
  GC.Collect();
  GC.WaitForPendingFinalizers();
}

    好多網友都在介紹使用GC.Collect()釋放EXCEL佔用的資源來結束EXCEL進行,如果將“GC.Collect();”與操作EXCEL的業務寫在一個程式塊中,“GC”是永遠不能結束EXCEL進程的,在WEB應用程式中,這種現象是很可怕的事情。原因是GC不會清理本程式塊中的垃圾記憶體的。

4、在業務事件中調用killEXCEL()方法:

複製代碼 代碼如下:
protected void LinkButton3_Click(object sender, EventArgs e)
{
  //匯出EXCEL
  killExcel();
}

八、一些許可權的基本設定:

使用以上方法在開發環境中偵錯工具沒有一點問題,等發布到伺服器上後,程式還是不能正常運行,需要進行如下的使用權限設定:

.NET匯出Excel遇到的80070005錯誤的解決方案:

檢索 COM 類別工廠中 CLSID 為 {00024500-0000-0000-C000-000000000046}的組件時失敗,原因是出現以下錯誤: 80070005基本上.net匯出excel檔案,都需要如此配置一下,不配置有的時候沒錯,而配置後基本應該不會出錯。
具體配置方法如下: 
① 在伺服器上安裝office的Excel軟體.
② 在"開始"->"運行"中輸入dcomcnfg.exe啟動"元件服務" 
③ 依次雙擊"元件服務"->"電腦"->"我的電腦"->"DCOM配置"
④ 在"DCOM配置"中找到"Microsoft  Excel 應用程式",在它上面點擊右鍵,然後點擊"屬性",彈出"Microsoft Excel 應用程式屬性"對話方塊 
⑤ 點擊"標識"標籤,選擇"互動式使用者" 
⑥ 點擊"安全"標籤,在"啟動和啟用許可權"上點擊"自訂",然後點擊對應的"編輯"按鈕,在彈出的"安全性"對話方塊中填加一個"NETWORK  SERVICE"使用者(注意要選擇本電腦名稱),並給它賦予"本地啟動"和"本地啟用"許可權. 
⑦ 依然是"安全"標籤,在"存取權限"上點擊"自訂",然後點擊"編輯",在彈出的"安全性"對話方塊中也填加一個"NETWORK  SERVICE"使用者,然後賦予"本地訪問"許可權. 
⑧ 如果互動式使用者佈建後出現錯誤8000401a,可取消互動式使用者,指定為administratr,可暫時解決此問題。進一步的解決方式還有待探討。 
⑨ 採用第8點的設定後,開啟Excel可能會出現“無法使用對象引用或連結”,並且不能進行儲存格粘貼。原因不明,取消設定後即可消失。

希望本文所述對大家的asp.net程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.