標籤:
關於匯出,屬於老生常談了,下面就總結下我自己遇到的一些匯出吧。
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