ASP.NET後台自訂匯出Excel

來源:互聯網
上載者:User

標籤:

關於匯出,屬於老生常談了,下面就總結下我自己遇到的一些匯出吧。

1、使用Excel組件進行匯出(需要安裝Microsoft Office Excel)。

下面為代碼,希望可以協助別人。

1)準備資料來源

//首先建立一個DataTableDataTable dtSource = new DataTable();dtSource.Columns.Add("ID");dtSource.Columns.Add("Name");dtSource.Columns.Add("Description");

//往DataTable中添加一些資料
for(int i=0;i<10;i++){
  DataRow row = dtSource.NewRow();
  row["ID"]=i+1;
  row["Name"]="Tom And Jerry";
  row["Description"]="這是一個經典的動畫片,貓和老鼠";
  dtSource.Rows.Add(row);
}

  string filePath = HttpContext.Current.Server.MapPath("~/UpFiles/file/aa.xls");

 2)建立Excel對象,並添加資料

//Microsoft.Office.Interop.Excel.Application excel = null;   //建立一個Office對象,或者使用Microsoft.Office.Interop.Excel._Application
  excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
  excel.Workbooks.Add(true);
  int rowIndex=1; //Excel中的行,從1開始
  int colIndex=1; //Excel中的列,從1開始
  //添加標題
 foreach(DataColumn col in dtSource.Columns){
   excel.Cells[rowIndex,colIndex] = col.ColumnName;
   colIndex++;
  }
  //添加表格內容
 foreach(DataRow row in dtSource.Rows){
   rowIndex++;
   colIndex = 1;
   foreach(DataColumn col in dtSource.Columns){
      excel.Cells[rowIndex,colIndex]=row[col.ColumnName].ToString();
      colIndex++;
   }
  }

  excel.ActiveWorkbook.SaveAs(filePath,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange
 ,Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);

  excel.Quit();
  excel = null;

 

 3)產生結果如所示

ASP.NET後台自訂匯出Excel

聯繫我們

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