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(); 
} 
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章