第一種最常見,並且最簡單的方式,直接把GridView導出,導出格式為文本表格形式。
protected void btnSaveExcel_Click(object sender, EventArgs e) { string FileName = "xxx"; System.IO.StringWriter objSW = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter objHTW = new System.Web.UI.HtmlTextWriter(objSW); try { //設定格式 Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FileName)); Response.ContentType = "application/ms-excel";// "application/vnd.ms-excel"; Response.Charset = "UTF-8"; this.EnableViewState = false; this.GridViewData.RenderControl(objHTW); Response.Write(objSW.ToString()); Response.End(); } catch (Exception ex) { string aa = ex.Message.ToString(); } finally { objSW.Close(); objSW = null; objHTW.Close(); objHTW = null; } } ///必須重載VerifyRenderingInServerForm, 不然會報錯 public override void VerifyRenderingInServerForm(Control control) { //base.VerifyRenderingInServerForm(control); }
第二種:不用安裝Excel,生成原生Excel格式方法
如果你和我一樣要實現不調用Excel組件實現Excel數據導出的話,那我嚴重向你推薦MyXls,MyXls是用C#開源項目,可以應用於asp.net 或者 .net應用程序上。它根據微軟公開的Excle文檔格式文件(BIFF),以二進制格式直接生成excel文檔,支持Excel versions 97 - 2007 。這意味着你可以不用在服務器上安裝office就能夠以excle格式輸出數據庫中存儲的數據了,這對於許多項目來說都是很有用的
第一步,當然是下在MyXls,地址:http://sourceforge.net/projects/myxls/
第二步,添加引用org.in2bits.MyXls.dll
第三步,實現數據導出,我這里是將一個DataTable作為數據導出,導出后內容格式和DataTable一致,具體代碼如下:
private void Output(DataTable dt) { org.in2bits.MyXls.XlsDocument doc = new org.in2bits.MyXls.XlsDocument(); doc.FileName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + ".xls";//excel文件名稱 org.in2bits.MyXls.Worksheet sheet = doc.Workbook.Worksheets.AddNamed("sheet1");//Excel工作表名稱 org.in2bits.MyXls.Cells cells = sheet.Cells; int colnum = dt.Columns.Count;//獲取DataTable列數 for (int i = 0; i < colnum; i++) { cells.Add(1, (i + 1), dt.Columns[i].Caption.ToString());//導出DataTable列名 } for (int i = 0; i < dt.Rows.Count; i++) { for (int j = 0; j < colnum; j++) { cells.Add((i + 2), (j + 1), dt.Rows[i][j].ToString()); } } //doc.Save(@"D:\"); //保存到指定位置 doc.Send();//把寫好的excel文件輸出到客戶端 }
生成多個WorkSheet
XlsDocument xls = new XlsDocument();//新建一個xls文檔 xls.FileName = "MyXlsDemo.xls";//設定Excel文件名 xls.SummaryInformation.Author = "Terry Li"; //填加Excel文件作者信息 xls.SummaryInformation.Subject = "MyXls Demo";//填加文件主題信息 xls.DocumentSummaryInformation.Company = "in2bits.org";//填加文件公司信息 string sheetName = "第一個Sheet Demo";#region string sheetName = "第一個Sheet Demo"; Worksheet sheet = xls.Workbook.Worksheets.Add(sheetName);//填加名為"第一個Sheet Demo"的sheet頁 Cells cells = sheet.Cells;//Cells實例是sheet頁中單元格(cell)集合 //單元格1-base Cell cell = cells.Add(2, 3, "三");//設定第2行,第3例單元格的值 cell.HorizontalAlignment = HorizontalAlignments.Centered;//設定文字居中 cell.Font.FontName = "行楷";//設定字體 cell.Font.Height = 30 * 20;//設定字大小(字體大小是以 1/20 point 為單位的) cell.UseBorder = true;//使用邊框 cell.BottomLineStyle = 2;//設定邊框底線為粗線 cell.BottomLineColor = Colors.Red;//設定顏色為紅色 cell.RightLineStyle = 2; cell.RightLineColor = Colors.Red; //cell的格式還可以定義在一個xf對象中 XF cellXF = xls.NewXF();//為xls生成一個XF實例(XF是cell格式對象) cellXF.HorizontalAlignment = HorizontalAlignments.Centered;//設定文字居中 cellXF.Font.FontName = "隸書";//設定字體 cellXF.Font.Height = 30 * 20;//設定字大小(字體大小是以 1/20 point 為單位的) cellXF.UseBorder = true;//使用邊框 cellXF.BottomLineStyle = 2;//設定邊框底線為粗線 cellXF.BottomLineColor = Colors.Green;//設定顏色為綠色 cellXF.LeftLineStyle = 2; //設定邊框左線為粗線 cellXF.LeftLineColor = Colors.Green; cell = cells.Add(3, 3, "國", cellXF);//以設定好的格式填加cell cellXF.Font.FontName = "仿宋_GB2312"; cellXF.BottomLineStyle = 2; //設定邊框底線為粗線 cellXF.BottomLineColor = Colors.Blue;//設定顏色為藍色 cellXF.RightLineStyle = 2;//設定邊框右線為粗線 cellXF.RightLineColor = Colors.Blue;//設定顏色為藍色 cellXF.LeftLineStyle = 0; cell = cells.Add(4, 3, "志", cellXF);//格式可以多次使用 //ColumnInfo colInfo = new ColumnInfo(xls, sheet);//生成列格式對象 ////設定colInfo格式的起作用的列為第2列到第5列(列格式為0-base) //colInfo.ColumnIndexStart = 1;//起始列為第二列 //colInfo.ColumnIndexEnd = 5;//終止列為第六列 //colInfo.Width = 15 * 256;//列的寬度計量單位為 1/256 字符寬 //sheet.AddColumnInfo(colInfo);//把格式附加到sheet頁上(注:AddColumnInfo方法有點小問題,不給把colInfo對象多次附給sheet頁) //colInfo.ColumnIndexEnd = 6;//可以更改列對象的值 //ColumnInfo colInfo2 = new ColumnInfo(xls, sheet);//通過新生成一個列格式對象,才到能設定其它列寬度 //colInfo2.ColumnIndexStart = 7; //colInfo2.ColumnIndexEnd = 8; //colInfo2.Width = 20 * 256; //sheet.AddColumnInfo(colInfo2); MergeArea meaA = new MergeArea(2, 3, 5, 7);//一個合並單元格實例(合並第2行、第5列 到 第3行、第7例) sheet.AddMergeArea(meaA);//填加合並單元格 cellXF.VerticalAlignment = VerticalAlignments.Centered; cellXF.Font.FontName = "隸書"; //cellXF.Font.Height = 48 * 20; //cellXF.Font.Bold = true; cellXF.Pattern = 1;//設定單元格填充風格。如果設定為0,則是純色填充(無色),1代表沒有間隙的實色 cellXF.PatternBackgroundColor = Colors.Red;//填充的底色 cellXF.PatternColor = Colors.Green;//設定填充線條的顏色 cell = cells.Add(2, 5, "晉/陳壽", cellXF); #endregion sheet.Cells.Merge(7, 9, 1, 4); cell = cells.Add(7, 1, "MyXls 合並單元格 Demo"); cell.HorizontalAlignment = HorizontalAlignments.Centered; cell.VerticalAlignment = VerticalAlignments.Centered; for (int sheetNumber = 1; sheetNumber <= 4; sheetNumber++) { sheetName = "Sheet " + sheetNumber; int rowMin = sheetNumber; int rowCount = sheetNumber + 10; int colMin = sheetNumber; int colCount = sheetNumber + 10; sheet = xls.Workbook.Worksheets.Add(sheetName); cells = sheet.Cells; for (int r = 0; r < rowCount; r++) { if (r == 0) { for (int c = 0; c < colCount; c++) { cells.Add(rowMin + r, colMin + c, "Column" + (c + 1)).Font.Bold = true; } } else { for (int c = 0; c < colCount; c++) { int val = r + c; cell = cells.Add(rowMin + r, colMin + c, val+ ":51CTO五歲了!"); if (val % 2 != 0) { cell.HorizontalAlignment = HorizontalAlignments.Centered; cell.Font.FontName = "Times New Roman"; cell.Font.Underline = UnderlineTypes.Double; cell.Font.ColorIndex = 2; cell.Rotation = 45; //字符傾斜45度 } } } } } xls.Send();//XlsDocument.SendMethods.Inline
效果

該代碼出自(http://terryli.blog.51cto.com/704315/392125)
