天天看點

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

wpf 導出Excel

1 private void Button_Click_1(object sender, RoutedEventArgs e)
  2 {
  3 
  4 ExportDataGridSaveAs(true, this.data);
  5 }
  6 #region wpf用戶端 導出DataGrid資料到Excel
  7 
  8 /// <summary>
  9 /// CSV格式化
 10 /// </summary>
 11 /// <param name="data">資料</param>
 12 /// <returns>格式化資料</returns>
 13 private static string FormatCsvField(string data)
 14 {
 15 return String.Format("\"{0}\"", data.Replace("\"", "\"\"\"").Replace("\n", "").Replace("\r", ""));
 16 }
 17 
 18  
 19 
 20 /// <summary>
 21 /// 導出DataGrid資料到Excel
 22 /// </summary>
 23 /// <param name="withHeaders">是否需要表頭</param>
 24 /// <param name="grid">DataGrid</param>
 25 /// <param name="dataBind"></param>
 26 /// <returns>Excel内容字元串</returns>
 27 public static string ExportDataGrid(bool withHeaders, System.Windows.Controls.DataGrid grid, bool dataBind)
 28 {
 29 try
 30 {
 31 var strBuilder = new System.Text.StringBuilder();
 32 var source = (grid.ItemsSource as System.Collections.IList);
 33 if (source == null) return "";
 34 var headers = new List<string>();
 35 List<string> bt = new List<string>();
 36 
 37 foreach (var hr in grid.Columns)
 38 {
 39 // DataGridTextColumn textcol = hr. as DataGridTextColumn;
 40 headers.Add(hr.Header.ToString());
 41 if (hr is DataGridTextColumn)//列綁定資料
 42 {
 43 DataGridTextColumn textcol = hr as DataGridTextColumn;
 44 if (textcol != null)
 45 bt.Add((textcol.Binding as Binding).Path.Path.ToString()); //擷取綁定源
 46 
 47 }
 48 else if (hr is DataGridTemplateColumn)
 49 {
 50 if (hr.Header.Equals("操作"))
 51 bt.Add("Id");
 52 }
 53 else
 54 {
 55 
 56 }
 57 }
 58 strBuilder.Append(String.Join(",", headers.ToArray())).Append("\r\n");
 59 foreach (var data in source)
 60 {
 61 var csvRow = new List<string>();
 62 foreach (var ab in bt)
 63 {
 64 string s = ReflectionUtil.GetProperty(data, ab).ToString();
 65 if (s != null)
 66 {
 67 csvRow.Add(FormatCsvField(s));
 68 }
 69 else
 70 {
 71 csvRow.Add("\t");
 72 }
 73 }
 74 strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\r\n");
 75 // strBuilder.Append(String.Join(",", csvRow.ToArray())).Append("\t");
 76 }
 77 return strBuilder.ToString();
 78 }
 79 catch (Exception ex)
 80 {
 81 // LogHelper.Error(ex);
 82 return "";
 83 }
 84 }
 85 public class ReflectionUtil
 86 {
 87 public static object GetProperty(object obj, string propertyName)
 88 {
 89 PropertyInfo info = obj.GetType().GetProperty(propertyName);
 90 if (info == null && propertyName.Split('.').Count() > 0)
 91 {
 92 object o = ReflectionUtil.GetProperty(obj, propertyName.Split('.')[0]);
 93 int index = propertyName.IndexOf('.');
 94 string end = propertyName.Substring(index + 1, propertyName.Length - index - 1);
 95 return ReflectionUtil.GetProperty(o, end);
 96 }
 97 object result = null;
 98 try
 99 {
100 result = info.GetValue(obj, null);
101 }
102 catch (TargetException)
103 {
104 return "";
105 }
106 return result == null ? "" : result;
107 }
108 }
109 /// <summary>
110 /// 導出DataGrid資料到Excel為CVS檔案
111 /// 使用utf8編碼 中文是亂碼 改用Unicode編碼
112 /// 
113 /// </summary>
114 /// <param name="withHeaders">是否帶列頭</param>
115 /// <param name="grid">DataGrid</param>
116 public static void ExportDataGridSaveAs(bool withHeaders, System.Windows.Controls.DataGrid grid)
117 {
118 try
119 {
120 string data = ExportDataGrid(true, grid, true);
121 var sfd = new Microsoft.Win32.SaveFileDialog
122 {
123 DefaultExt = "csv",
124 Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*",
125 FilterIndex = 1
126 };
127 if (sfd.ShowDialog() == true)
128 {
129 using (Stream stream = sfd.OpenFile())
130 {
131 using (var writer = new StreamWriter(stream, System.Text.Encoding.Unicode))
132 {
133 data = data.Replace(",", "\t");
134 writer.Write(data);
135 writer.Close();
136 }
137 stream.Close();
138 }
139 }
140 MessageBox.Show("導出成功!");
141 }
142 catch (Exception ex)
143 {
144 // LogHelper.Error(ex);
145 }
146 }
147 
148 #endregion 導出DataGrid資料到Excel
149 
150        

 找了好多都有問題,這個可以分享給到家

轉自:https://www.cnblogs.com/kmust/p/4412228.html

Wpf Button 樣式

上圖檔:

預設                  滑鼠懸浮        滑鼠按下

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合
wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合
wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合
<Window.Resources>
<Style x:Key="ButtonFocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#F3F3F3" Offset="0"/>
<GradientStop Color="#EBEBEB" Offset="0.5"/>
<GradientStop Color="#DDDDDD" Offset="0.5"/>
<GradientStop Color="#CDCDCD" Offset="1"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">

<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border Name="border" BorderThickness="1" BorderBrush="{TemplateBinding Background}" Background="{TemplateBinding Background}" CornerRadius="20">
<Label Name="label" FontSize="15" Content="{TemplateBinding Content}" VerticalAlignment="Center" HorizontalAlignment="Center" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></Label>
</Border>
<!-- <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding IsDefaulted}" SnapsToDevicePixels="true">
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Themes:ButtonChrome>-->
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="Green"></Setter>
<Setter Property="BorderBrush" TargetName="border" Value="Green"></Setter>
<Setter TargetName="label" Property="FontSize" Value="16"></Setter>
<Setter TargetName="label" Property="Foreground" Value="yellow"></Setter>

</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" TargetName="border" Value="Yellow"></Setter>
<Setter Property="BorderBrush" TargetName="border" Value="Yellow"></Setter>
<Setter TargetName="label" Property="FontSize" Value="17"></Setter>
<Setter TargetName="label" Property="Foreground" Value="Green"></Setter>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<Button Width="100" Height="40" Content="點選" Background="Gray" Style="{DynamicResource ButtonStyle1}" Click="Button_Click"/>
</Grid>

</Window>      

wpf簡單進度條

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合
UserControl x:Class="WpfApplication1.UserControl2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:ed="http://schemas.microsoft.com/expression/2010/drawing"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:local="clr-namespace:WpfApplication1"

mc:Ignorable="d" 
d:DesignHeight="300" d:DesignWidth="300" >


<Viewbox>
<Grid>
<Border Name="MaxCircle" CornerRadius="500" Width="100" Height="100" Background="White" Opacity="0.2"/>

<ed:Arc Name="FillArea" ArcThickness="0.02" ArcThicknessUnit="Percent" StartAngle="0" EndAngle="0" Width="95" Height="95" Stretch="None" Opacity="0.8" Fill="#86E02D"/>
<Label Name="ShowLabel" Width="60" Height="60" FontFamily="宋體" FontWeight="Bold" Content="01" FontSize="32" Foreground="Black" Opacity="0.8" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" />
</Grid>
</Viewbox>
</UserControl>      

List泛型集合對象排序

本文的重點主要是解決:List<T>對象集合的排序功能。

一、List<T>.Sort 方法 ()

MSDN對這個無參Sort()方法的介紹:使用預設比較器對整個List<T>中的元素進行排序。

從官方文檔的介紹,很難的看出詳細的解析,而且還要完整的知識結構去分析,上面提到了一個關鍵詞:比較器。大緻看了下,比較器是一個委托。在這裡不去透析它的完整脈絡,本文隻去講解怎麼去解決兩個實際的問題:

  • List集合元素升序排列
  • List集合元素降序排列

1.1.對于數字類型的調用

調用結果:為升序,無法滿足降序。

示例:

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

 1.2.對于字元串類型的調用

調用結果:把值解析成拼音字母,按照首個英文字母順序升序排列,如果首字母相同,比較第二個的首字母。

示例:

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

1.3.對于自定義對象的調用

調用結果:無法完成方法的執行,運作報錯。

示例:

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

總結:很顯然這個無參的Sort()方法很難滿足我們實際開發中需求,對于面向對象程式設計我們,常常就是對集合中的對象進行排序。

二、自定義對象類型預設排序

對象本身不是一個具體的值,在排序邏輯上顯然要選擇對象的一個屬性進行排序。

1.1手動設定無參Sotr()方法的預設排序邏輯

将List的指定類型的類實作IComparable泛型接口,示例:

1     class Student:IComparable<Student>
 2     {
 3         
 4         public string Id { get; set; }
 5         public string Name { get; set; }
 6         public int Age { get; set; }
 7 
 8         public int CompareTo(Student other)
 9         {
10             //return other.Age.CompareTo(this.Age); // 年齡降序
11             return this.Age.CompareTo(other.Age); // 年齡升序
12         }
13     }      

排序邏輯:this在前面就意味着指定按照這個屬性升序,如果寫在後面就是降序。 

調用:

List<Student> list_obj = new List<Student> { 
               new Student { Age=23,Name="tom"},
               new Student { Age=18,Name="jack"},
               new Student {Age=28, Name="bob"},
            };

            list_obj.Sort();

            for (int i = 0; i < list_obj.Count; i++)
            {
                string output_result = string.Format("{0},年齡:{1}",list_obj[i].Name,list_obj[i].Age);
                Console.WriteLine(output_result);
            }      

在調用Sort()方法的時候,就自動調用了我們實作接口的CompareTo方法的邏輯代碼。

結果如圖:

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

總結:此方法的實作,雖然解決了可以按照對象屬性進行升序和降序,但是在實作CompareTo的方法裡,指定的屬性是固定的。這樣的話顯然

 不靈活,那麼下面就介紹另一種方法,解決該問題。

二、自定義對象類型動态排序

預設排序,通過實作IComparable泛型接口來完成。并且在實作ComparaTo接口裡指定排序的屬性是固定的,寫死的。如果功能上有多條件排序(按照年齡、學号等等),預設排序就無法滿足。

1.1為每一個要排序的屬性寫一個對應的排序類,一個排序邏輯對應一個排序類,示例:

//按照Id升序
    class StudentOrderBy_Id_asc:IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
           return x.Id.CompareTo(y.Id);
        }
    }
    
    //按照年齡降序
    class StudentOrderBy_Age_desc:IComparer<Student>
    {
        public int Compare(Student x, Student y)
        {
            return y.Age.CompareTo(x.Age);
        }
    }      

1.2.調用

List<Student> list_obj = new List<Student> { 
               new Student { Id=9,Age=23,Name="tom"},
               new Student { Id=3,Age=18,Name="jack"},
               new Student {Id=10,Age=28, Name="bob"},
                new Student {Id=2,Age=30, Name="ben"},
            };

            //---按照ID升序----
            list_obj.Sort(new StudentOrderBy_Id_asc());
            Console.WriteLine("---按照ID升序----");
            for (int i = 0; i < list_obj.Count; i++)
            {
                string output_result = string.Format("{0},學号:{1}",list_obj[i].Name,list_obj[i].Id);           
                Console.WriteLine(output_result);
            }
            //---END按照ID升序----


            //---按照年齡降序----
            list_obj.Sort(new StudentOrderBy_Age_desc());
            Console.WriteLine("---按照年齡降序----");
            for (int i = 0; i < list_obj.Count; i++)
            {
                string output_result = string.Format("{0},年齡:{1}", list_obj[i].Name, list_obj[i].Age);
                Console.WriteLine(output_result);
            }
            //---END按照年齡降序----      

 1.3.輸出結果:

wpf 導出Excel Wpf Button 樣式 wpf簡單進度條 List泛型集合對象排序 C#集合wpf 導出ExcelWpf Button 樣式wpf簡單進度條List泛型集合對象排序C#集合

1.4編寫邏輯:

  1. 确定好要排序的屬性和排序規則,為此寫一個排序類。
  2. 編寫Compare方法的排序邏輯(指定排序屬性,排序邏輯)。
  3. 建立排序類的對象,作為參數參入,調用Sort()方法。

 總結:本文主要是解決實際問題,要深入到細節原理,會涉及到一些知識點:冒泡排序、多态、比較器、委托。

   在具備知識點的前提結合Msdn文檔可以嘗試透析原理。

C#集合

一、 集合概述

  沒有掌握集合的知識之前,我們通常都是用數組來存儲元素。數組有一個很明顯的特點就是,長度是固定的。假設,用數組存儲一組員工資訊,顯然公司的員工數量是有流動性的,如果來了新員工,那麼以現有的知識來思考,這個數組隻能重新定義。能否建立一個動态的 “數組”,使我們可以對其進行動态的操作呢?下面就引入集合,來解決這個問題。

 二、ArrayList

 ArrayList屬于非泛型集合,現在大多數情況用的很少了。文章裡會首先介紹非泛型集合,是因為引出泛型集合,就像通過數組引出集合的概念一樣。

ArrayList可能會介紹的詳細一點,這都是為了後面的内容做鋪墊。

1.簡介

ArrayList非常類似于數組,可以填補數組的不足,進行元素的動态維護。數組的長度是固定的,而ArrayList的容量可以根據需要自動擴充,它的索引會根據程式的擴充而重新配置設定和調整。

ArrayList是可以動态維護的,是以在定義的時候可以指定容量,也可以不指定容量。

如圖:

2.給ArrayList添加資料

 a.通過Add()方法添加元素

 Add()方法是将元素添加到集合結尾處,傳回一個int類型,用于傳回所添加元素的索引。

重點:如果Add()添加的元素是值類型,這些元素都會裝箱處理轉換為Object引用類型。是以ArrayList中所有的元素都是引用類型。

b.通過集合初始化器構造集合

3.存取ArrayList中的單個元素

 ArrayList擷取一個元素的方法和數組是一樣的,也是通過索引來通路。需要注意的是,由于元素添加時都會被轉換為object類型,是以在通路元素的時候必須把他們轉換成原來的資料類型。

4.删除ArrayList中的元素

4.1.RemoveAt()根據索引删除指定元素。

使用索引删除元素還是存在一定的風險:

運作後,發現系統異常,因為ArrayList的索引會自動配置設定和調整,在上圖注意事項1的集合中添加了三個元素,删除第一個元素後,索引為“2”的第三個元素就不存在了,長度動态的發生了變化,是以再删除索引為“2”的元素就會發生錯誤。如果存在索引為“2”的元素,那麼删除之前和删除之後是兩個不同的對象,這時候會導緻資料不對。是以使用索引删除元素還是存在一定的風險的。

4.2.Remove()指定對象删除。

4.3.Clear()删除集合所有元素。

三、Hashtable

對于ArrayList集合我們通常會使用索引通路操作元素,但是這樣的話就存在一個問題,使用這種方式必須知道要操作的索引是多少。

Hashtable可以針對這種情況解決問題,它為每個元素都取了一個有意義并且唯一的關鍵字,然後通過關鍵字來通路元素。

Hashtable,通常稱為哈希表,也有人稱它為“字典”。使用字典這個名詞,是因為其數成非常類似于現實生活中的字典。Hashtable的資料是通過(key)鍵和值(value)來組織的。

如圖:

1.添加元素:

Add(key,value)

2.擷取Hashtable元素

2.1.和ArrayList不同,通路Hashtable元素時隻能使用通過鍵名來擷取具值。

如圖:

用索引通路,程式運作時會提示“未将對象引用設定到對象的示例”。

2.2.由于添加時值被隐試轉換為object類型,是以當從集合中擷取元素時要通過類型轉換得到指定類型對象。

示例:

2.3.删除Hashtable的元素:

通過鍵(key),使用Remove()方法就可以删除。

2.4.周遊Hashtable中的元素

由于Hashtable不能使用索引通路,是以周遊一個Hashtable隻能用foreach()方法:

周遊Hashtable中的對象:

四、泛型集合

前面介紹了兩種非泛型集合,Hashtable和ArrayList。在實際開發過程中,用的很少了,說明這兩個集合也是為了對講解和學習泛型集合有一個好的鋪墊。

非泛型集合對元素的資料類型沒有限制性,在添加時資料類型都會被轉為Object類型,這意味着集合中可以加入不同的資料類型的資料。那麼這樣對資料的操作會有什麼影響呢?

示例:

在添加的時候沒有限制類型,讀取的時候也不知道對象的具體的類型,是以在元素資料類型轉換的時候就存在了不确定性。有沒有什麼好的方法限制集合中元素的資料類型呢?下面就來介紹使用泛型集合來儲存資料。泛型集合限定了集合中的資料類型。

1.泛型集合List<T>

1.1.文法:List<T> 對象名 = new List<T>();

“<T>”需要指定一個資料類型,将T替換換指定資料類型後就可以對集合中的元素的資料類型進行限制。

1.2.泛型集合List<T>添加、擷取、删除元素以及周遊的方法和ArrayList的用法都是類似的。但是List<T>在周遊通路元素時無需做類型轉換。

示例:

1.3.List<T>與ArrayList的差別

2.泛型集合Dictionary<K,V>

Dictionary<K,V>集合類似于前面所講的Hashtable,也是通過Key/value(鍵/值)對元素儲存的。

它具有泛型的全部特性,編譯時檢查類型限制,擷取元素時隻能通過key而不能通過索引,并且擷取元素時無需類型轉換。

2.1.文法:

Dictionary<K,V> 對項目 = new Dictionary<K,V>();

說明:K表示集合中指定Key的類型,V表示Value的類型。他們的含義和List<T>是相同的。

2.2.Dictionary<K,V>集合的常用(添加、删、擷取)操作方法和Hashtable是一樣的,在這裡不詳細介紹。

示例:

2.3.周遊Dictionary<K,V>集合:

KeyValuePair<Tkey,Tvalue>是一個泛型結構,定義可設定或者檢索的鍵/值對。詳細内容可以查閱MSDN。

2.4.Dictionary<K,V>和Hashtable的對比:

總結:本文隻是對集合做了基礎和細節的介紹,集合在開發中通常用來存儲對象,而在實際的開發中還要結合實際功能深入去學習怎麼去運用才是關鍵。

轉載于:https://www.cnblogs.com/cjm123/p/9058503.html

c#