积极答复者
asp.net如何通过模版导出Excel

问题
答案
全部回复
-
这是我的导出Excel,不知道为什么模版不管用。
private void OutputExcel(DataTable dt) { string Filename = "/Templates.xls"; GC.Collect(); Excel.Application excel; Excel._Workbook xBk; Excel._Worksheet xSt; excel = new Excel.ApplicationClass(); xBk = excel.Workbooks.Add(true); xSt = (Excel._Worksheet)xBk.ActiveSheet; for (int i = 0; i < dt.Rows.Count; i++) { //int officeid = Convert.ToInt32(ds.Tables[0].Rows[i][3].ToString()); //DateTime stdt = Convert.ToDateTime(ds.Tables[0].Rows[i][4].ToString()); excel.Cells[i + 3, 1] = dt.Rows[i][2].ToString(); excel.Cells[i + 3, 2] = dt.Rows[i][3].ToString(); excel.Cells[i + 3, 3] = dt.Rows[i][4].ToString(); excel.Cells[i + 3, 4] = dt.Rows[i][5].ToString(); excel.Cells[i + 3, 5] = dt.Rows[i][6].ToString(); excel.Cells[i + 3, 6] = dt.Rows[i][7].ToString(); excel.Cells[i + 3, 7] = dt.Rows[i][8].ToString(); excel.Cells[i + 3, 8] = dt.Rows[i][9].ToString(); excel.Cells[i + 3, 9] = dt.Rows[i][10].ToString(); excel.Cells[i + 3, 10] = dt.Rows[i][11].ToString(); excel.Cells[i + 3, 11] = dt.Rows[i][12].ToString(); excel.Cells[i + 3, 12] = dt.Rows[i][13].ToString(); excel.Cells[i + 3, 13] = dt.Rows[i][14].ToString(); excel.Cells[i + 3, 14] = dt.Rows[i][15].ToString(); excel.Cells[i + 3, 15] = dt.Rows[i][16].ToString(); excel.Cells[i + 3, 16] = dt.Rows[i][17].ToString(); excel.Cells[i + 3, 17] = dt.Rows[i][18].ToString(); excel.Cells[i + 3, 18] = dt.Rows[i][19].ToString(); excel.Cells[i + 3, 19] = dt.Rows[i][20].ToString(); excel.Cells[i + 3, 20] = dt.Rows[i][21].ToString(); excel.Cells[i + 3, 21] = dt.Rows[i][22].ToString(); excel.Cells[i + 3, 22] = dt.Rows[i][23].ToString(); excel.Cells[i + 3, 23] = dt.Rows[i][24].ToString(); } excel.Columns.AutoFit(); //显示效果 excel.Visible = true; xBk.SaveCopyAs(Server.MapPath(".") + "\\" + Filename); 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(Filename); System.IO.FileInfo file = new System.IO.FileInfo(path); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode("表_" + DateTime.Now.ToShortDateString() + ".xls")); Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文 EnableViewState = false; Response.WriteFile(file.FullName); Response.End(); }