對於數據導出網上數不勝數,但是圖表卻寥寥無幾,可能我沒搜到吧。。。。html
這個方法感受對於EXCEL模板的要求比較高,模板作的好導出來的效果相對完美一點,導出的數據如果動態行列的不妨看下以下這篇,先作好一份好的模板ajax
https://www.zhihu.com/question/48727312/answer/113147034sql
順便再放一個縱向折線圖畫法數據庫
http://www.officedoyen.com/a/exceltubiao/yibantubiao/zhexiantu/2015/0714/10795.htmlspa
接下來就是一些代碼了excel
js代碼,寫一個點擊事件訪問後臺方法,後面跟本身要加的參數code
//導出點擊事件 $("#btExport").click(function () { window.open("/text/ajax/export.aspx?Method=export&language=" +c.language); });
後臺代碼orm
DBClass db = new DBClass(); MemoryStream ms = new MemoryStream(); IWorkbook workbook = new HSSFWorkbook(); //模板路徑,從ajax的上一層test找到excel文件下的模板.xls string excelTempPath = Server.MapPath("~/test/") + "/excel/模板.xls"; //讀取Excel模板 using (FileStream fs = new FileStream(excelTempPath, FileMode.Open, FileAccess.Read)) { workbook = new HSSFWorkbook(fs); } ISheet sheet = workbook.GetSheetAt(0);//表示在模板的第一個工做簿裏寫入 IRow headerRow = sheet.CreateRow(0); try { //string starttime = Request.Params["Ssss"].ToString();//後臺取出傳來的數據 //假若是ajax的方式傳值用MyForm["Method"].ToString().ToLower() //讀取數據庫的名稱 DataTable newTable = new DataTable(); SqlCommand comm; DataSet ds; string sql = "這裏寫取數據的sql" comm = db.getSqlCommand(sql); ds = db.getDataSetBySqlCommand(comm); //下面這部分通常人不須要能夠刪掉 newTable = ds.Tables[0].Copy(); DataRow dr = newTable.NewRow(); int BSum = 0; int PNum = 0; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { BSum += int.Parse(ds.Tables[0].Rows[i][1].ToString()); PNum += int.Parse(ds.Tables[0].Rows[i][2].ToString()); } object[] objs = { "業務部", BSum, PNum }; dr.ItemArray = objs; newTable.Rows.Add(dr); //新插入一行數據 DataTable table = newTable; int k = 0; string language = Request.Params["language"].ToString();
//如下仍是有必要的加上頭部名稱 foreach (DataColumn column in table.Columns) {
// headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption)//加上爲列名的頭部
if (language == "zh-cn") {
//設置自定義頭部名稱 headerRow.CreateCell(column.Ordinal).SetCellValue(deptbusinessTitle[k].Split(',')[0]); } else { headerRow.CreateCell(column.Ordinal).SetCellValue(deptbusinessTitle[k].Split(',')[1]); } k++; } int rowIndex = 1; foreach (DataRow row in table.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); int colnum = 0; foreach (DataColumn column in table.Columns) { if (colnum == 0)//導入excel時一些數據列必須是int類型的,不然它就不會本身繪製 { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } else { dataRow.CreateCell(column.Ordinal).SetCellValue(int.Parse(row[column].ToString())); } colnum++; } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; string fileName = "導出文件.xls"; if (Request.Browser.Browser == "IE") fileName = HttpUtility.UrlEncode(fileName); Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName); Response.BinaryWrite(ms.ToArray()); } catch (Exception e) { throw e; } finally { db.CloseConn(); }