1、將數據寫入HTTP輸出流/這樣子導出以後的數據全在一行中
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(); }
2、打開一個excel將數據逐行寫入
需要添加兩個com引用
Microsoft Office 15.0 Object Library
Microsoft Excel 15.0 Object Library
public bool DataSetToExcel(DataSet dataSet, bool isShowExcle) { DataTable dataTable = dataSet.Tables[0]; int rowNumber = dataTable.Rows.Count; int columnNumber = dataTable.Columns.Count; if (rowNumber == 0) { //MessageBox.Show("沒有任何數據可以導入到Excel文件!"); return false; } else { Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); excel.Application.Workbooks.Add(true); excel.Visible = isShowExcle;//是否打開該Excel文件 for (int c = 0; c < rowNumber; c++) { for (int j = 0; j < columnNumber; j++) { excel.Cells[c + 1, j + 1] = dataTable.Rows[c].ItemArray[j]; } } return true; } }