原创不易,打字不易,截图不易,多多点赞,送人玫瑰,留有余香,财务自由明日实现
1、添加用户控件
<UserControl x:Class="West.StoreMgr.View.DataExportView"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:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:West.StoreMgr.View"xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"mc:Ignorable="d" DataContext="{Binding Source={StaticResource Locator},Path=DataExport}"d:DesignHeight="450" d:DesignWidth="800"><i:Interaction.Triggers><i:EventTrigger EventName="Loaded"><i:InvokeCommandAction Command="{Binding LoadCommand}"/></i:EventTrigger></i:Interaction.Triggers><Grid><Grid.RowDefinitions><RowDefinition Height="50"/><RowDefinition /><RowDefinition Height="auto"/></Grid.RowDefinitions><!--标题--><StackPanel Background="#EDF0F6" Orientation="Horizontal"><TextBlock Margin="10 0 0 0" Text="" FontSize="20" FontFamily="/Fonts/#FontAwesome" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="#797672"/><TextBlock Margin="10 0 0 0" Text="首页 > 数据导出" FontSize="20" FontFamily="/Fonts/#FontAwesome" HorizontalAlignment="Left" VerticalAlignment="Center" Foreground="#797672"/></StackPanel><!--Tabcontrol--><Grid Grid.Row="1" Margin="20"><TabControl ItemsSource="{Binding TabItems}"/></Grid><!--button--><Grid Grid.Row="2" Margin="10 10 10 10"><Button Height="36" Width="120" Grid.Row="3" HorizontalAlignment="Right"Content="一键导出" Style="{StaticResource ButtonStyle}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=local:DataExportView}}"Command="{Binding BackupCommand}"/></Grid></Grid>
</UserControl>
2、添加viewmodel
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows;
using System.IO;
using GalaSoft.MvvmLight.Command;
using West.StoreMgr.Service;
using West.StoreMgr.Control;
using West.StoreMgr.Helper;
using West.StoreMgr.Model;namespace West.StoreMgr.ViewModel
{/// <summary>/// 数据导出viewmodel/// </summary>public class DataExportViewModel : ViewModelBase{private List<Customer> customers = new List<Customer>();private List<Goods> goods = new List<Goods>();private List<GoodsType> goodsTypes = new List<GoodsType>();private List<InStore> inStores = new List<InStore>();private List<Inventory> inventories = new List<Inventory>();private List<OutStore> outStores = new List<OutStore>();private List<OutStore_temp> outStoresTemp = new List<OutStore_temp>();private List<Spec> specs = new List<Spec>();private List<Store> stores = new List<Store>();private List<Supplier> suppliers = new List<Supplier>();private List<UserInfo> userInfos = new List<UserInfo>();private ObservableCollection<TabItem> tabItems = new ObservableCollection<TabItem>();/// <summary>/// tab选项集合/// </summary>public ObservableCollection<TabItem> TabItems{get { return tabItems; }set { tabItems = value; RaisePropertyChanged(); }}public RelayCommand LoadCommand{get{return new RelayCommand(() =>{customers = new CustomerService().Select();goods = new GoodsService().Select();goodsTypes = new GoodsTypeService().Select();inStores = new InStoreService().Select();inventories = new InventoryService().Select();outStores = new OutStoreService().Select();outStoresTemp = BuildList(outStores);specs = new SpecService().Select();stores = new StoreService().Select();suppliers = new SupplierService().Select();userInfos = new UserInfoService().Select();tabItems.Add(new TabItem { Header = "客户表", Content = new TableControl { DataContext = customers } });tabItems.Add(new TabItem { Header = "物资表", Content = new TableControl { DataContext = goods } });tabItems.Add(new TabItem { Header = "物资类别表", Content = new TableControl { DataContext = goodsTypes } });tabItems.Add(new TabItem { Header = "入库表", Content = new TableControl { DataContext = inStores } });tabItems.Add(new TabItem { Header = "盘存表", Content = new TableControl { DataContext = inventories } });tabItems.Add(new TabItem { Header = "出库表", Content = new TableControl { DataContext = outStoresTemp } });tabItems.Add(new TabItem { Header = "规格表", Content = new TableControl { DataContext = specs } });tabItems.Add(new TabItem { Header = "仓库表", Content = new TableControl { DataContext = stores } });tabItems.Add(new TabItem { Header = "供应商表", Content = new TableControl { DataContext = suppliers } });tabItems.Add(new TabItem { Header = "用户表", Content = new TableControl { DataContext = userInfos } });});}}/// <summary>/// 构建新的出库实体(原实体具有扩展属性,这是不必要的)/// </summary>/// <param name="outStores"></param>/// <returns></returns>List<OutStore_temp> BuildList(List<OutStore> outStores){List<OutStore_temp> list = new List<OutStore_temp>();foreach(OutStore item in outStores){OutStore_temp temp = new OutStore_temp();temp.Id = item.Id;temp.GoodsSerial = item.GoodsSerial;temp.Name = item.Name;temp.StoreId = item.StoreId;temp.StoreName = item.StoreName;temp.CustomerId = item.CustomerId;temp.CustomerName = item.CustomerName;temp.Unit = item.Unit;temp.Number = item.Number;temp.Price = item.Price;temp.InsertDate = item.InsertDate;temp.GoodsTypeId = item.GoodsTypeId;temp.UserInfoId = item.UserInfoId;temp.UserInfoName = item.UserInfoName;temp.Tag = item.Tag;temp.IsInventory = item.IsInventory; list.Add(temp); }return list;}/// <summary>/// 导出命令/// </summary>public RelayCommand BackupCommand{get{return new RelayCommand(() =>{Backup(customers, "customers");Backup(goods, "goods");Backup(goodsTypes, "goodsTypes");Backup(inStores, "inStores");Backup(inventories, "inventories");Backup(outStoresTemp, "outStores");Backup(specs, "specs");Backup(stores, "stores");Backup(suppliers, "suppliers");Backup(userInfos, "userInfos");});}}/// <summary>/// 导出数据/// </summary>/// <param name="array">列表对象</param>/// <param name="filename">文件名称</param>/// <exception cref="NotImplementedException"></exception>private void Backup<T>(List<T> array, string name){var t = typeof(T);var properties = t.GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);var contents = new StringBuilder();//标题foreach (var item in properties){//得到第一个自定义属性的参数的值,即属性描述var desc = item.CustomAttributes.ToList()[0].ConstructorArguments[0].Value.ToString(); contents.Append(desc);contents.Append(",");} contents.Append("\r\n");//换行//内容foreach (var model in array){var row = new StringBuilder();foreach (var property in properties){var val = property.GetValue(model);row.Append(val);row.Append(",");}contents.Append(row.ToString());contents.Append("\r\n");}//finename -> 表格+日期var date = $"{DateTime.Now.Year}-{DateTime.Now.Month}-{DateTime.Now.Day}";var filename = $"c:\\{name}{date}.csv";//保存File.WriteAllText(filename, contents.ToString(),Encoding.UTF8);//以utf-8的格式保存成csv格式MsgWinHelper.ShowMessage("数据导出完成");}}
}
3、运行效果