效果:javascript
數據庫端:css
前端展現:html
實現原理:前端
1.在數據段創建兩個存儲過程java
queryUserAnsawer(id) 根據用戶ID返回每一題的得分,主要是bcp exe時不能直接在sqlserver中執行sql查詢語句,只能先調用存儲過程git
exportUserAnsawer(id,filepath,re)根據指定的ID調用queryUserAnsawer,根據物理路徑導出csv文件,re用來判斷導出是否成功github
2.使用aps.net的cs文件生成filepath,而後調用exportUserAnsawer導出文件sql
3.使用d3.js獲取導出的csv文件,而後可視化顯示。可查看我以前的文章:shell
源碼及分析:數據庫
1.sql存儲過程的創建(導出user的總分到CSV文件.sql)
Use 你的數據庫名 go --建立存儲過程,根據userID返回每一題的分值 if exists (SELECT * FROM sysobjects WHERE name='queryUserAnsawer') drop proc exportQueryUserAnsawer go create proc queryUserAnsawer @id int as --這裏能夠自定義sql語句 select 題庫.題編號 題編號, (選項一分值*A+選項二分值*B+選項三分值*C+選項四分值*D) 總分 from dbo.會員答案,題庫 WHERE 會員編號=@id and 會員答案.題編號=題庫.題編號 go --調用存儲過程exportQueryUserAnsawer exec 你的數據庫名..queryUserAnsawer 1 -- 建立函數,根據userID返回每一題的總分,並將其保存到自定義CSV的文件中 if exists (SELECT * FROM sysobjects WHERE name='exportUserAnsawer') drop proc exportUserAnsawer go create proc exportUserAnsawer ( @id int ,@filepath varchar(8000),--輸入參數 @re int output --輸出參數 ) as declare @s varchar(8000) --csv文件的表頭,你也能夠自定義表頭,可是爲了與前端d3.js訪問,直接就data1,data2了set @s='echo data1,data2>"'+@filepath+'"' exec master..xp_cmdshell @s,no_output --導出csv文件到temp目錄 set @s='bcp "exec 數據庫名..queryUserAnsawer '+cast(@id as varchar(50))+'" queryout "'+'"%temp%\temp.csv"'+'" /c /t, /U"登陸名" -P"密碼" /S 服務器名' exec master..xp_cmdshell @s ,no_output --將temp目錄下的csv文件與以前的csv文件的表頭合併 set @s='more %temp%\temp.csv >>"'+@filepath+'"' exec master..xp_cmdshell @s ,no_output --刪除temp目錄下的csv文件 exec master..xp_cmdshell 'del %temp%\temp.csv' ,no_output --返回執行結果 set @re=1 --若是能夠執行這一句表明以前的語句沒有報錯 go --調用存儲過程exportUserAnsawer --F:\Data\data.csv declare @w int exec 數據庫名..exportUserAnsawer 5, 'F:\Data\data.csv' ,@w output --PRINT '執行結果:'+CONVERT(varchar(20),@w) select @w as '返回值'
2.在網站目錄下的app_code建立一個用於導出文件的類(DB.cs)
using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; /// <summary> /// DB 的摘要說明 /// </summary> public class DB { public SqlConnection Con = new SqlConnection(); public SqlCommand Com = new SqlCommand(); public SqlDataAdapter Da = new SqlDataAdapter(); public DataSet Ds = new DataSet(); public DB() { // // TODO: 在此處添加構造函數邏輯 // } //定義一個用於返回數據庫鏈接字符串的方法 public String GetConnectionString() { String ConStr; // ConStr = System.Configuration.ConfigurationManager.AppSettings.Get("con").ToString(); // ConStr = System.Configuration.ConfigurationManager.ConnectionStrings["textconnectionstring"].ToString(); ConStr = System.Configuration.ConfigurationManager.ConnectionStrings["鏈接名"].ToString(); return ConStr; } //根據userID返回每一題的總分,並將其保存到自定義CSV的文件中 //調用存儲過程exportUserAnsawer public bool exportQueryUserAnsawer(int id, String filepath) { int re = 0; try { Con.ConnectionString = GetConnectionString(); //打開鏈接 Con.Open(); //調用存儲過程 Com = new SqlCommand("exportUserAnsawer", Con); //設置命令的類型爲存儲過程 Com.CommandType = CommandType.StoredProcedure; // 設置參數 Com.Parameters.Add("@id", SqlDbType.Int); Com.Parameters.Add("@filepath", SqlDbType.VarChar); // 注意輸出參數要設置大小,不然size默認爲0 Com.Parameters.Add("@re", SqlDbType.Int, 10); // 設置參數的類型爲輸出參數,默認狀況下是輸入, Com.Parameters["@re"].Direction = ParameterDirection.Output; // 爲參數賦值 Com.Parameters["@id"].Value = id; Com.Parameters["@filepath"].Value = filepath; // 執行 Com.ExecuteNonQuery(); // 獲得輸出參數的值,把賦值給re,注意,這裏獲得的是object類型的,要進行相應的類型轉換 re = (int)Com.Parameters["@re"].Value; if (re == 1) return true; else return false; } catch (Exception e){ // Console.WriteLine(e.ToString()); return false; } } }
3.在後端(測試結果.cs)文件中,建立文件名,路徑,用戶ID。這些變量能夠從其餘頁面的Session中獲取,我這裏就寫死了(方便演示)。
測試結果.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { String filepath=null; String userID = null; String username = null; protected void Page_Load(object sender, EventArgs e) { userID = ""+5; username = "clientuser1"; //插入數據完成後導出csv文件 filepath = getFilePath(username, userID); DB db2 = new DB(); if (db2.exportQueryUserAnsawer(Convert.ToInt16(userID), filepath)) { Response.Write("<script>alert('保存文件成功');</script>"); } else { Response.Write("<script>alert('⚠保存文件失敗');</script>"); } //轉相對路徑 filepath = urlconvertor(filepath); //以上變量可從session中獲取 //try //{ // username = Session["ClientUsername"].ToString(); // userID = Session["ClientUserID"].ToString(); // filepath = Session["FliePath"].ToString(); // filepath = urlconvertor(filepath); // // Response.Write(filepath + "<br/>"); //} //catch //{ // Response.Write("<script>alert('請先登陸!');;window.location.href='登陸.aspx';</script>"); // return; //} //設置如下屬性是爲了,實現與js數據交互 this.name.Text = username; this.name.ToolTip = username; this.path.ToolTip = filepath; } //退出登陸 protected void Button1_Click(object sender, EventArgs e) { Session.Clear(); Response.Redirect("登陸.aspx"); } //生成文件物理路徑 以下 //F:\Demo\Data\username_5_answer_2019-05-08_18-29-48-792.csv protected String getFilePath(String username,String userID ) { String year = DateTime.Now.Year.ToString(); String mouth = DateTime.Now.Month.ToString(); String day = DateTime.Now.Day.ToString(); String houre = DateTime.Now.Hour.ToString(); String minute = DateTime.Now.Minute.ToString(); String second = DateTime.Now.Second.ToString(); String millsecond = DateTime.Now.Millisecond.ToString(); if (Convert.ToInt16(mouth) < 10) mouth = "0" + mouth; if (Convert.ToInt16(day) < 10) day = "0" + day; String date = year + "-" + mouth + "-" + day + "_" + houre + "-" + minute + "-" + second + "-" + millsecond; //Response.Write(date); //插入完成後導出csv文件 filepath = "\\Data\\" + username + "_" + userID + "_answer_" + date + ".csv"; filepath = urlconvertorlocal(filepath); return filepath; } //轉絕對路徑 private string urlconvertorlocal(string url) { string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//獲取程序根目錄 string reurl = tmpRootDir + url.Replace(@"/", @"/"); //轉換成絕對路徑 return reurl; } //本地路徑轉換成URL相對路徑 private string urlconvertor(string url) { string tmpRootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString())+"\\";//獲取程序根目錄 string reurl = url.Replace(tmpRootDir, ""); //轉換成相對路徑 reurl = reurl.Replace("\\", "/"); return reurl; } }
4.前端代碼
測試結果.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="測試結果.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>測試結果</title> <style type="text/css"> .hidden { display:none } .choice { display:block } </style> <script type="text/javascript" src="js/d3.min.js"></script> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="name" runat="server" Text="username"></asp:Label> <%--爲了c#與js交互--%> <asp:Label ID="path" runat="server" Text="path" class="hidden" ></asp:Label> <asp:Button ID="Button1" runat="server" Text="退出登陸" onclick="Button1_Click" /> <%--使用頁面回發響應慢,使用JS控制--%> <div id="radio"> <asp:RadioButton ID="RadioButton1" runat="server" Text="條形圖" GroupName="g1" Checked="true" /> <asp:RadioButton ID="RadioButton2" runat="server" Text="面積圖" GroupName="g1" /> <asp:RadioButton ID="RadioButton3" runat="server" Text="柱狀圖" GroupName="g1" /> <asp:RadioButton ID="RadioButton4" runat="server" Text="餅狀圖" GroupName="g1" /> </div> <asp:Panel ID="Pane_LineChart" runat="server" class="choice"> <link href="css/linechart.css" type="text/css" media="screen" rel="Stylesheet" /> <div id="linechart_container"> <div id="linechart"> </div> </div> <script type="text/javascript" src="js/linechart.js"></script> </asp:Panel> <asp:Panel ID="Panel_AreaChart" runat="server" class="hidden"> <link href="css/areachart.css" type="text/css" media="screen" rel="Stylesheet" /> <div id="areachart_container"> <div id="areachart"> </div> </div> <script type="text/javascript" src="js/areachart.js"></script> </asp:Panel> <asp:Panel ID="Panel_BarChart" runat="server" class="hidden"> <link href="css/barchart.css" type="text/css" media="screen" rel="Stylesheet" /> <div id="barchart"> </div> <script type="text/javascript" src="js/barchart.js"></script> </asp:Panel> <asp:Panel ID="Panel_PieChart" runat="server" class="hidden"> <link href="css/piechart.css" type="text/css" media="screen" rel="Stylesheet" /> <div id="piechart"> </div> <script type="text/javascript" src="js/piechart.js"></script> </asp:Panel> </div> </form> <script type="text/javascript" src="js/radioButton.js"></script> </body> </html>
我上面只寫了關鍵代碼,若是你想查看整個demo,請在這裏下載