C# 將資料匯出到Excel匯總

來源:互聯網
上載者:User

 

一、asp.net中匯出Excel的方法:

在asp.net中匯出Excel有兩種方法,一種是將匯出的檔案存放在伺服器某個檔案夾下面,然後將檔案地址輸出在瀏覽器上;一種是將檔案直接將檔案輸出資料流寫給瀏覽器。在Response輸出時,t分隔的資料,匯出Excel時,等價於分列,n等價於換行。
1、將整個html全部輸出Excel

此法將html中所有的內容,如按鈕,表格,圖片等全部輸出到Excel中。

   Response.Clear();    
   Response.Buffer=   true;    
   Response.AppendHeader("Content-Disposition","attachment;filename="+DateTime.Now.ToString("yyyyMMdd")+".xls");          
   Response.ContentEncoding=System.Text.Encoding.UTF8;  
   Response.ContentType   =   "application/vnd.ms-excel";  
   this.EnableViewState   =   false;  

這裡我們利用了ContentType屬性,它預設的屬性為text/html,這時將輸出為超文本,即我們常見的網頁格式到用戶端,如果改為ms-excel將將輸出excel格式,也就是說以試算表的格式輸出到用戶端,這時瀏覽器將提示你下載儲存。ContentType的屬性還包括:image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 。同理,我們也可以輸出(匯出)圖片、word文檔等。下面的方法,也均用了這個屬性。

2、將DataGrid控制項中的資料匯出Excel

上述方法雖然實現了匯出的功能,但同時把按鈕、分頁框等html中的所有輸出資訊導了進去。而我們一般要匯出的是資料,DataGrid控制項上的資料。

System.Web.UI.Control ctl=this.DataGrid1;
//DataGrid1是你在表單中拖放的控制項
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";
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();

如果你的DataGrid用了分頁,它匯出的是當前頁的資訊,也就是它匯出的是DataGrid中顯示的資訊。而不是你select語句的全部資訊。

為方便使用,寫成方法如下:

public void DGToExcel(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";
   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();
  }

   用法:DGToExcel(datagrid1);
  
3、將DataSet中的資料匯出Excel

有了上邊的思路,就是將在匯出的資訊,輸出(Response)用戶端,這樣就可以匯出了。那麼把DataSet中的資料匯出,也就是把DataSet中的表中的各行資訊,以ms-excel的格式Response到http流,這樣就OK了。說明:參數ds應為填充有資料表的DataSet,檔案名稱是全名,包括尾碼名,如Excel2006.xls

public  void CreateExcel(DataSet ds,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="";   
 
 //定義表對象與行對象,同時用DataSet對其值進行初始化
 DataTable dt=ds.Tables[0];
 DataRow[] myRow=dt.Select();//可以類似dt.Select("id>10")之形式達到資料篩選目的
        int i=0;
        int cl=dt.Columns.Count;
    
 //取得資料表各欄位標題,各標題之間以t分割,最後一個欄位標題後加斷行符號符
 for(i=0;i<cl;i++)
 {
 if(i==(cl-1))//最後一列,加n
 {
 colHeaders +=dt.Columns[i].Caption.ToString() +"n";
 }
 else
 {
 colHeaders+=dt.Columns[i].Caption.ToString()+"t";
 }
      
 }
 resp.Write(colHeaders);
 //向HTTP輸出資料流中寫入取得的資料資訊
   
 //逐行處理資料  
 foreach(DataRow row in myRow)
 {     
 //當前行資料寫入HTTP輸出資料流,並且置空ls_item以便下行資料    
 for(i=0;i<cl;i++)
 {
 if(i==(cl-1))//最後一列,加n
 {
 ls_item +=row[i].ToString()+"n";
 }
 else
 {
 ls_item+=row[i].ToString()+"t";
 }
  
 }
 resp.Write(ls_item);
 ls_item="";
    
 }    
 resp.End(); 
 }

4、將dataview匯出excel
若想實現更加富於變化或者行列不規則的excel匯出時,可用本法。

public void OutputExcel(DataView dv,string str)
{
   //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資料,直接給瀏覽器輸出檔案流,下面的方法是首先將其存到伺服器的某個檔案夾中,然後把檔案發送到用戶端。這樣可以持久的把匯出的檔案存起來,以便實現其它功能。
5、將excel檔案匯出到伺服器上,再下載。

二、winForm中匯出Excel的方法:

1、方法1:

   SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   DataTable dt=ds.Tables["table1"];
   string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路徑,檔案格式為當前日期+4位隨機數
   FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
   StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
   sw.WriteLine("自動編號,姓名,年齡");
   foreach(DataRow dr in dt.Rows)
   {
    sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
   }
   sw.Close();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
   Response.ContentType = "application/ms-excel";// 指定返回的是一個不能被用戶端讀取的流,必須被下載
   Response.WriteFile(name); // 把檔案流發送到用戶端
   Response.End();

 

public void Out2Excel(string sTableName,string url)
{
Excel.Application oExcel=new Excel.Application();
Workbooks oBooks;
Workbook oBook;
Sheets oSheets;
Worksheet oSheet;
Range oCells;
string sFile="",sTemplate="";
//
System.Data.DataTable dt=TableOut(sTableName).Tables[0];

sFile=url+"myExcel.xls";
sTemplate=url+"MyTemplate.xls";
//
oExcel.Visible=false;
oExcel.DisplayAlerts=false;
//定義一個新的活頁簿
oBooks=oExcel.Workbooks;
oBooks.Open(sTemplate,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing, Type.Missing, Type.Missing);
oBook=oBooks.get_Item(1);
oSheets=oBook.Worksheets;
oSheet=(Worksheet)oSheets.get_Item(1);
//命名該sheet
oSheet.Name="Sheet1";

oCells=oSheet.Cells;
//調用dumpdata過程,將資料匯入到Excel中去
DumpData(dt,oCells);
//儲存
oSheet.SaveAs(sFile,Excel.XlFileFormat.xlTemplate,Type.Missing,Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing);
oBook.Close(false, Type.Missing,Type.Missing);
//退出Excel,並且釋放調用的COM資源
oExcel.Quit();

GC.Collect();
KillProcess("Excel");
}

private void KillProcess(string processName)
{
System.Diagnostics.Process myproc= new System.Diagnostics.Process();
//得到所有開啟的進程
try
{
foreach (Process thisproc in Process.GetProcessesByName(processName))
{
if(!thisproc.CloseMainWindow())
{
thisproc.Kill();
}
}
}
catch(Exception Exc)
{
throw new Exception("",Exc);
}
}

2、方法2:

 

protected void ExportExcel()
  {
   gridbind();
   if(ds1==null) return;
 
   string saveFileName="";
//   bool fileSaved=false;
   SaveFileDialog saveDialog=new SaveFileDialog();
   saveDialog.DefaultExt ="xls";
   saveDialog.Filter="Excel檔案|*.xls";
   saveDialog.FileName ="Sheet1";
   saveDialog.ShowDialog();
   saveFileName=saveDialog.FileName;
   if(saveFileName.IndexOf(":")<0) return; //被點了取消
//   excelapp.Workbooks.Open   (App.path & 工程進度表.xls)
  
   Excel.Application xlApp=new Excel.Application();
   object missing=System.Reflection.Missing.Value;
 

   if(xlApp==null)
   {
    MessageBox.Show("無法建立Excel對象,可能您的機子未安裝Excel");
    return;
   }
   Excel.Workbooks workbooks=xlApp.Workbooks;
   Excel.Workbook workbook=workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
   Excel.Worksheet worksheet=(Excel.Worksheet)workbook.Worksheets[1];//取得sheet1
   Excel.Range range;
   
 
   string oldCaption=Title_label .Text.Trim ();
   long totalCount=ds1.Tables[0].Rows.Count;
   long rowRead=0;
   float percent=0;
 
   worksheet.Cells[1,1]=Title_label .Text.Trim ();
   //寫入欄位
   for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
   {
    worksheet.Cells[2,i+1]=ds1.Tables[0].Columns.ColumnName; 
    range=(Excel.Range)worksheet.Cells[2,i+1];
    range.Interior.ColorIndex = 15;
    range.Font.Bold = true;
 
   }
   //寫入數值
   Caption .Visible = true;
   for(int r=0;r<ds1.Tables[0].Rows.Count;r++)
   {
    for(int i=0;i<ds1.Tables[0].Columns.Count;i++)
    {
     worksheet.Cells[r+3,i+1]=ds1.Tables[0].Rows[r];    
    }
    rowRead++;
    percent=((float)(100*rowRead))/totalCount;   
    this.Caption.Text= "正在匯出資料["+ percent.ToString("0.00")  +"%]...";
    Application.DoEvents();
   }
   worksheet.SaveAs(saveFileName,missing,missing,missing,missing,missing,missing,missing,missing);
   
   this.Caption.Visible= false;
   this.Caption.Text= oldCaption;
 
   range=worksheet.get_Range(worksheet.Cells[2,1],worksheet.Cells[ds1.Tables[0].Rows.Count+2,ds1.Tables[0].Columns.Count]);
   range.BorderAround(Excel.XlLineStyle.xlContinuous,Excel.XlBorderWeight.xlThin,Excel.XlColorIndex.xlColorIndexAutomatic,null);
  
   range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].ColorIndex = Excel.XlColorIndex.xlColorIndexAutomatic;
   range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].LineStyle =Excel.XlLineStyle.xlContinuous;
   range.Borders[Excel.XlBordersIndex.xlInsideHorizontal].Weight =Excel.XlBorderWeight.xlThin;
 
   if(ds1.Tables[0].Columns.Count>1)
   {
    range.Borders[Excel.XlBordersIndex.xlInsideVertical].ColorIndex=Excel.XlColorIndex.xlColorIndexAutomatic;
    }
   workbook.Close(missing,missing,missing);
   xlApp.Quit();
  }

三、附註:
雖然都是實現匯出excel的功能,但在asp.net和winform的程式中,實現的代碼是各不相同的。在asp.net中,是在伺服器端讀取資料,在伺服器端把資料以ms-excel的格式,以Response輸出到瀏覽器(用戶端);而在winform中,是把資料讀到用戶端(因為winform運行端就是用戶端),然後調用用戶端安裝的office組件,將讀到的資料寫在excel的活頁簿中。 
v

相關文章

聯繫我們

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