前言
之前在網上找了很多關于狀態圖的資料,但是很少是在winform上實現的。其實堆疊柱狀圖是來自于PPT的一種數據統計方式,展示給用戶直觀的圖片印象。而C#很多時候要展現比較精美的界面都采用WPF來實現,像winform的技術一直沒有更新,控件中只有老舊的chart控件,很難實現我們的需求,因此在winform平臺上要實現堆疊柱狀圖需要引入第三方插件,調用的是百度開源的echart。
echart官網:
https://www.echartsjs.com/examples/zh/index.html
準備
1,首先在bin文件夾中下載添加echarts.js和echarts.min.js文件,echarts.min.js是需要自己在官網定制的。可以參考:https://blog.csdn.net/weixin_42528089/article/details/95487734
-
2,在winform窗口添加WebBrowser控件,屬性Dock可以選在Fill填充整個窗口,我選擇的是None可以自定義拉伸尺寸。下面是界面展示:
主界面.png -
3,開始添加各功能模塊的內容:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MyEchart { //設置Com對外可訪問 [System.Runtime.InteropServices.ComVisible(true)] public partial class Form1 : Form { /// <summary> /// 根目錄 /// </summary> string str = System.Environment.CurrentDirectory; public Form1() { InitializeComponent(); //初始化瀏覽器 this.initWebBrowser(); //加載 文件 this.getAllHtmlFile(); } private void button1_Click(object sender, EventArgs e) { HTML.AddHtml("index1"); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { this.webBrowser1.Dispose(); } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { this.webBrowser1.Url = new Uri(str + "\\" + comboBox1.Text.Trim()); } private void button2_Click(object sender, EventArgs e) { comboBox1.Items.Clear(); this.getAllHtmlFile(); } /// <summary> /// 刷新 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button3_Click(object sender, EventArgs e) { this.webBrowser1.Refresh(); } /// <summary> /// 獲取html文件 /// </summary> private void getAllHtmlFile() { //獲取指定文件夾的所有文件 string[] paths = Directory.GetFiles(str); foreach (var item in paths) { //獲取文件后綴名 string extension = Path.GetExtension(item).ToLower(); if (extension == ".html") { comboBox1.Items.Add(Path.GetFileName(item)); } } if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; this.webBrowser1.Url = new Uri(str + "\\" + comboBox1.Text.Trim()); } } private void Form1_Load(object sender, EventArgs e) { //瀏覽器url 取到index.html頁面 //this.webBrowser1.Url = new Uri(str + "\\index.html"); //if (comboBox1.Items.Count > 0) //{ // comboBox1.SelectedIndex = 0; // this.webBrowser1.Url = new Uri(str +"\\"+ comboBox1.Text.Trim()); //} } /// <summary> /// 初始化瀏覽器 /// </summary> private void initWebBrowser() { //防止 WebBrowser 控件打開拖放到其上的文件。 webBrowser1.AllowWebBrowserDrop = false; //防止 WebBrowser 控件在用戶右擊它時顯示其快捷菜單. webBrowser1.IsWebBrowserContextMenuEnabled = false; //以防止 WebBrowser 控件響應快捷鍵。 webBrowser1.WebBrowserShortcutsEnabled = false; //以防止 WebBrowser 控件顯示腳本代碼問題的錯誤信息。 webBrowser1.ScriptErrorsSuppressed = true; //(這個屬性比較重要,可以通過這個屬性,把WINFROM中的變量,傳遞到JS中,供內嵌的網頁使用;但設置到的類型必須是COM可見的,所以要設置 [System.Runtime.InteropServices.ComVisibleAttribute(true)],因為我的值設置為this,所以這個特性要加載窗體類上) webBrowser1.ObjectForScripting = this; } } }
同時,為了可以添加HTML文件和修改HTML,增加HTML.cs文件,源代碼如下:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace MyEchart
{
public struct HTML
{
public static void EditHtml(string fileName)
{
Stream myStream = new FileStream(fileName, FileMode.Open);
//Encoding encode = System.Text.Encoding.GetEncoding("GB2312");
Encoding encode = System.Text.Encoding.GetEncoding("UTF-8");
StreamReader myStreamReader = new StreamReader(myStream, encode);
string strhtml = myStreamReader.ReadToEnd();
//string stroutput = strhtml.Replace("&*平均溫度*&", "要替換的內容平均溫度");
string stroutput = strhtml.Replace("123", "123456");
myStream.Seek(0, SeekOrigin.Begin);
myStream.SetLength(0);
StreamWriter sw = new StreamWriter(myStream, encode);
sw.Write(stroutput);
sw.Flush();
sw.Close();
myStream.Close();
}
public static void AddHtml(string path)
{
try
{
string fileName = path + ".html";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
using (StreamWriter sw = new StreamWriter(fileName, false))
{
//sw.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
//sw.WriteLine("<html xmlns=\"http://www.w3.org/1999/xhtml\">");
//sw.WriteLine("<head>");
//sw.WriteLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
//sw.WriteLine("<title> </title>");
//sw.WriteLine("</head>");
//sw.WriteLine("<body>");
//sw.WriteLine("<img src=" + path + ">");
//sw.WriteLine("</body>");
//sw.WriteLine("</html>");
sw.WriteLine("<!DOCTYPE html>");
sw.WriteLine("<html>");
sw.WriteLine("<head>");
sw.WriteLine(" <meta charset=\"utf-8\">");
sw.WriteLine(" <title>ECharts</title>");
sw.WriteLine(" <!-- 引入 echarts.js -->");
sw.WriteLine(" <script src=\"echarts.js\"></script>");
sw.WriteLine("</head>");
sw.WriteLine("<body>");
sw.WriteLine(" <!-- 為ECharts準備一個具備大小(寬高)的Dom -->");
sw.WriteLine(" <div id=\"main\" style=\"width: 1132px;height:516px;\"></div>");
sw.WriteLine(" <script type=\"text/javascript\">");
sw.WriteLine(" // 基于準備好的dom,初始化echarts實例");
sw.WriteLine(" var myChart = echarts.init(document.getElementById('main'));");
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine(" option = {");
sw.WriteLine(" tooltip: {");
sw.WriteLine(" trigger: 'axis',");
sw.WriteLine(" axisPointer: {");
sw.WriteLine(" type: 'cross',");
sw.WriteLine(" crossStyle: {");
sw.WriteLine(" color: '#999'");
sw.WriteLine(" }");
sw.WriteLine(" }");
sw.WriteLine(" },");
sw.WriteLine(" toolbox: {");
sw.WriteLine(" feature: {");
sw.WriteLine(" dataView: {show: true, readOnly: false},");
sw.WriteLine(" magicType: {show: true, type: ['line', 'bar']},");
sw.WriteLine(" restore: {show: true},");
sw.WriteLine(" saveAsImage: {show: true}");
sw.WriteLine(" }");
sw.WriteLine(" },");
sw.WriteLine(" legend: {");
sw.WriteLine(" data:['蒸發量','降水量', '1']");
sw.WriteLine(" },");
sw.WriteLine(" xAxis: [");
sw.WriteLine(" {");
sw.WriteLine(" type: 'category',");
sw.WriteLine(" data: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'],");
sw.WriteLine(" axisPointer: {");
sw.WriteLine(" type: 'shadow'");
sw.WriteLine(" }");
sw.WriteLine(" }");
sw.WriteLine(" ],");
sw.WriteLine(" yAxis: [");
sw.WriteLine(" {");
sw.WriteLine(" type: 'value',");
sw.WriteLine(" name: '水量',");
sw.WriteLine(" min: 0,");
sw.WriteLine(" max: 250,");
sw.WriteLine(" interval: 50,");
sw.WriteLine(" axisLabel: {");
sw.WriteLine(" formatter: '{value} ml'");
sw.WriteLine(" }");
sw.WriteLine(" },");
sw.WriteLine(" {");
sw.WriteLine(" type: 'value',");
sw.WriteLine(" name: '溫度',");
sw.WriteLine(" min: 0,");
sw.WriteLine(" max: 25,");
sw.WriteLine(" interval: 5,");
sw.WriteLine(" axisLabel: {");
sw.WriteLine(" formatter: '{value} °C'");
sw.WriteLine(" }");
sw.WriteLine(" }");
sw.WriteLine(" ],");
sw.WriteLine(" series: [");
sw.WriteLine(" {");
sw.WriteLine(" name:'蒸發量',");
sw.WriteLine(" type:'bar',");
sw.WriteLine(" stack:'堆疊',//堆疊柱狀圖在此設置成統一名稱即可");
sw.WriteLine(" data:[2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]");
sw.WriteLine(" },");
sw.WriteLine(" {");
sw.WriteLine(" name:'降水量',");
sw.WriteLine(" type:'bar',");
sw.WriteLine(" stack:'堆疊',//堆疊柱狀圖在此設置成統一名稱即可");
sw.WriteLine(" data:[2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3]");
sw.WriteLine(" },");
sw.WriteLine(" {");
sw.WriteLine(" name:'1',");
sw.WriteLine(" type:'line',");
sw.WriteLine(" yAxisIndex: 1,");
sw.WriteLine(" data:[2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]");
sw.WriteLine(" }");
sw.WriteLine(" ]");
sw.WriteLine("};");
sw.WriteLine("");
sw.WriteLine(" // 使用剛指定的配置項和數據顯示圖表。");
sw.WriteLine(" myChart.setOption(option);");
sw.WriteLine(" </script>");
sw.WriteLine("</body>");
sw.WriteLine("</html>");
sw.Close();
}
}
catch(ArithmeticException ex)
{
Console.WriteLine(ex);
}
}
}
}
以上是構建的所有源代碼,歡迎交流。
///////////////////////我是分割線*///////////////////////////
(2019年12月30日補充)
當然啦,我們看到的官網HTML文件是開源的,我們要想拿過來直接用,就要自己制作HTML文件了。
散點圖.png
將左側的源代碼放進debug文件夾的準備生成的文件.txt中,使用以下代碼轉換便可得到HTML文件了。
public static void MakOptionFile(string path)
{
//獲取應用程序的當前工作目錄
string filepath = System.IO.Directory.GetCurrentDirectory();
try
{
string fileName = path + ".txt";
if (File.Exists(fileName))
{
File.Delete(fileName);
}
using (StreamWriter sw = new StreamWriter(fileName, false))
{
string[] strs = File.ReadAllLines(filepath+ @"\準備生成的文件.txt", System.Text.Encoding.GetEncoding("gb2312"));
foreach(string strTemp in strs)
{
sw.WriteLine("sw.WriteLine(\""+ strTemp + "\");");
}
sw.Close();
}
}
catch (ArithmeticException ex)
{
Console.WriteLine(ex);
}
}
通過以上步驟,便可在winform平臺創建堆疊柱狀圖了,按照慣例,在文章末尾貼上一張效果圖吧。^ - ^
效果圖.png