// 1 定义类
using System;using System.Net;using System.windows;using System.windows.Data;using System.windows.Controls;using System.windows.documents;using System.windows.Ink;using System.windows.input;using System.windows.Media;using System.windows.Media.Animation;using System.windows.Shapes;using System.Reflection.Emit;using System.Reflection;using System.Collections;using System.Collections.Generic;using System.Text.RegularExpressions;using System.IO;using System.Xml.linq;using System.linq;using System.windows.Navigation;namespace SLApplicationMadaming.VIEws.第2部分调试.MSOfficeExcel导入导出{ public static class DataSourceCreator { private static Readonly Regex PropertnameRegex = new Regex(@"^[A-Za-z]+[A-Za-z1-9_]*$",RegexOptions.Singleline); public static IEnumerable ToDataSource(this IEnumerable<IDictionary> List) { IDictionary firstDict = null; bool hasData = false; foreach (IDictionary currentDict in List) { hasData = true; firstDict = currentDict; break; } if (!hasData) { return new object[] { }; } if (firstDict == null) { throw new ArgumentException("IDictionary entry cannot be null"); } Type objectType = null; TypeBuilder tb = GetTypeBuilder(List.GetHashCode()); ConstructorBuilder constructor = tb.defineDefaultConstructor( MethodAttributes.Public | MethodAttributes.Specialname | MethodAttributes.RTSpecialname); foreach (DictionaryEntry pair in firstDict) { //if (PropertnameRegex.IsMatch(Convert.ToString(pair.Key),0)) // { CreateProperty(tb,Convert.ToString(pair.Key),pair.Value == null ? typeof(object) : pair.Value.GetType()); /* } else { throw new ArgumentException() ; }*/ } objectType = tb.CreateType(); return GenerateEnumerable(objectType,List,firstDict); } private static IEnumerable GenerateEnumerable( Type objectType,IEnumerable<IDictionary> List,IDictionary firstDict) { var ListType = typeof(List<>).MakeGenericType(new[] { objectType }); var listofCustom = Activator.CreateInstance(ListType); foreach (var currentDict in List) { if (currentDict == null) { throw new ArgumentException("IDictionary entry cannot be null"); } var row = Activator.CreateInstance(objectType); foreach (DictionaryEntry pair in firstDict) { if (currentDict.Contains(pair.Key)) { PropertyInfo property = objectType.GetProperty(Convert.ToString(pair.Key)); property.SetValue( row,Convert.ChangeType( currentDict[pair.Key],property.PropertyType,null),null); } } ListType.getmethod("Add").Invoke(listofCustom,new[] { row }); } return listofCustom as IEnumerable; } private static TypeBuilder GetTypeBuilder(int code) { Assemblyname an = new Assemblyname("TempAssembly" + code); AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.defineDynamicAssembly( an,AssemblyBuilderAccess.Run); ModuleBuilder moduleBuilder = assemblyBuilder.defineDynamicModule("MainModule"); TypeBuilder tb = moduleBuilder.defineType("TempType" + code,TypeAttributes.Public | TypeAttributes.Class | TypeAttributes.autoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFIEldInit | TypeAttributes.autoLayout,typeof(object)); return tb; } private static voID CreateProperty( TypeBuilder tb,string propertyname,Type propertyType) { FIEldBuilder fIEldBuilder = tb.defineFIEld("_" + propertyname,propertyType,FIEldAttributes.Private); PropertyBuilder propertyBuilder = tb.defineProperty( propertyname,PropertyAttributes.HasDefault,null); MethodBuilder getPropMthdBldr = tb.defineMethod("get_" + propertyname,MethodAttributes.Public | MethodAttributes.Specialname | MethodAttributes.HIDeBySig,Type.EmptyTypes); ILGenerator getIL = getPropMthdBldr.GetILGenerator(); getIL.Emit(OpCodes.Ldarg_0); getIL.Emit(OpCodes.Ldfld,fIEldBuilder); getIL.Emit(OpCodes.Ret); MethodBuilder setPropMthdBldr = tb.defineMethod("set_" + propertyname,MethodAttributes.Public | MethodAttributes.Specialname | MethodAttributes.HIDeBySig,null,new Type[] { propertyType }); ILGenerator setIL = setPropMthdBldr.GetILGenerator(); setIL.Emit(OpCodes.Ldarg_0); setIL.Emit(OpCodes.Ldarg_1); setIL.Emit(OpCodes.Stfld,fIEldBuilder); setIL.Emit(OpCodes.Ret); propertyBuilder.Setgetmethod(getPropMthdBldr); propertyBuilder.SetSetMethod(setPropMthdBldr); } } public class madamingWorksheet { /// <summary> /// worksheet_name:工作表名 /// header_name:表头名表 /// header_key:表头bind键值表 /// headers:表头 /// rows: 表值表 /// </summary> string _worksheet_name; List<string> _header_values = new List<string>(); List<string> _header_keys = new List<string>(); List<List<string>> _headers = new List<List<string>>(); List<string> _row = new List<string>(); List<List<string>> _rows = new List<List<string>>(); #region 属性 public string Worksheetname { get { return _worksheet_name; } set { _worksheet_name = value; } } public List<string> headerValues { get { return _header_values; } } public List<string> headerKeys { get { return _header_keys; } } public List<List<string>> headers { get { _headers.Clear(); //_header_keys.Clear(); //for (int i = 0; i < _header_values.Count(); i++) //{ // string bind_path = string.Format("B{0:D2}",i); // _header_keys.Add(bind_path); //} _headers.Add(_header_keys); _headers.Add(_header_values); return _headers; } } public List<List<string>> Rows { get { return _rows; } } #endregion } public class madamingExcelXMLWorkSheetimport { #region 内部成员 private Stream _excel_xml_stream; private Xdocument xdoc2; madamingWorksheet _worksheet; List<madamingWorksheet> _worksheets = new List<madamingWorksheet>(); List<string> row; bool loadingheaders = false; object[] objects = new object[2]; #endregion #region 属性 public List<madamingWorksheet> WorkSheets { get { return _worksheets; } } #endregion #region 方法 #region - 构造方法 public madamingExcelXMLWorkSheetimport(Stream excel_xml_stream) { _excel_xml_stream = excel_xml_stream; xdoc2 = Xdocument.Load(_excel_xml_stream); browserXElement(xdoc2.Elements()); } #endregion #region 一般方法 private voID browserXElement(IEnumerable<XElement> xelements) { foreach (XElement e in xelements) { if (e.name.Localname == "Workbook") { browserWorkbook(e.Elements()); } } } private voID browserWorkbook(IEnumerable<XElement> xelements) { foreach (XElement e in xelements) { if (e.name.Localname == "Worksheet") { _worksheet = new madamingWorksheet(); if (e.HasAttributes) { foreach (XAttribute a in e.Attributes()) { if (a.name.Localname == "name") { _worksheet.Worksheetname = a.Value; break; } } } browserWorksheet(e.Elements()); _worksheets.Add(_worksheet); } } } private voID browserWorksheet(IEnumerable<XElement> xelements) { foreach (XElement e in xelements) { if (e.name.Localname == "table") { browsertable(e.Elements()); } } } private voID browsertable(IEnumerable<XElement> xelements) { //int c = xelements.Count(); int row_count = 0; foreach (XElement e in xelements) { if (e.name.Localname == "Row") { browserRow(row_count,e.Elements()); row_count++; } } } private voID browserRow(int row_number,IEnumerable<XElement> xelements) { int cell_count = 0; if (row_number == 0) { /// /// 处理首行列名 /// _worksheet.headerValues.Clear(); _worksheet.headerKeys.Clear(); foreach (XElement e in xelements) { if (e.name.Localname == "Cell") { browserheaderCell(cell_count,e.Elements()); cell_count++; } } } else { /// /// 后续行表值 /// row = new List<string>(); foreach (XElement e in xelements) { if (e.name.Localname == "Cell") { browserValueCell(cell_count,e.Elements()); cell_count++; } } _worksheet.Rows.Add(row); } } private voID browserheaderCell(int cell_number,IEnumerable<XElement> xelements) { string s1; string s2; foreach (XElement e in xelements) { if (e.name.Localname == "Data") { _worksheet.headerValues.Add(e.Value); string bind_path = string.Format("B{0:D2}",_worksheet.headerValues.Count()-1); _worksheet.headerKeys.Add(bind_path); if (e.HasAttributes) { foreach (XAttribute a in e.Attributes()) { s1 = a.name.Localname; s2 = a.Value; ; } } } } } private voID browserValueCell(int cell_number,IEnumerable<XElement> xelements) { string s1; string s2; string value; if (xelements.Count() > 0) { foreach (XElement e in xelements) { if (e.name.Localname == "Data") { value = e.Value; row.Add(value); if (e.HasAttributes) { foreach (XAttribute a in e.Attributes()) { s1 = a.name.Localname; s2 = a.Value; ; } } } } } else { value = string.Format("cell:{0}",cell_number); row.Add(value); } } private IEnumerable<IDictionary> GenerateData(int worksheet_index) { var values = _worksheets[worksheet_index].headerValues;// headers.First(); var key = _worksheets[worksheet_index].headerKeys;// headers.Last(); foreach (List<string> row in _worksheets[worksheet_index].Rows) { var dict = new Dictionary<string,object>(); for (int j = 0; j < key.Count(); j++) { dict[key[j]] = row[j]; } yIEld return dict; } } private voID GeerateDataGrIDheaders(DataGrID datagrID_显示,int worksheet_index ) { var values = _worksheets[worksheet_index].headerValues;// headers.First(); var key = _worksheets[worksheet_index].headerKeys;// headers.Last(); if (loadingheaders == false) { datagrID_显示.Columns.Clear(); datagrID_显示.autoGenerateColumns = false; for (int i = 0; i < key.Count(); i++) { DataGrIDTextColumn c = new DataGrIDTextColumn(); c.header = values[i]; c.Binding = new Binding(key[i]); datagrID_显示.Columns.Add(c); loadingheaders = true; } } } public voID GenerateDataGrIDData(DataGrID datagrID_显示,int worksheet_index) { GeerateDataGrIDheaders(datagrID_显示,worksheet_index); datagrID_显示.ItemsSource = GenerateData(worksheet_index).ToDataSource(); } #endregion #endregion }}
<navigation:Page xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="SLApplicationMadaming.VIEws.第2部分调试.Page_MSOfficeExcel导入导出" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/Expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" xmlns:navigation="clr-namespace:System.windows.Controls;assembly=System.windows.Controls.Navigation" d:DesignWIDth="640" d:DesignHeight="480" title="Page_MSOfficeExcel导入导出 Page"> <navigation:Page.Resources > <Style x:Key="hyperlinkbutton_style" @R_502_3609@="Hyperlinkbutton" > <Setter Property="VerticalAlignment" Value="Center" ></Setter> <Setter Property="margin" Value="10 0"></Setter> <Setter Property="Foreground" Value="Blue" ></Setter> </Style> </navigation:Page.Resources> <GrID x:name="LayoutRoot"> <GrID.RowDeFinitions> <RowDeFinition Height="25"></RowDeFinition> <RowDeFinition Height="*"></RowDeFinition> <RowDeFinition Height="25"></RowDeFinition> </GrID.RowDeFinitions> <StackPanel OrIEntation="Horizontal" GrID.Row="0" > <Hyperlinkbutton name="hyperlinkbutton_导入ExcelXML文件" Content="导入ExcelXML文件" Style="{StaticResource hyperlinkbutton_style}" Click="hyperlinkbutton_导入ExcelXML文件_Click" ></Hyperlinkbutton> <Hyperlinkbutton Content="导出ExcelXML文件" Style="{StaticResource hyperlinkbutton_style}"></Hyperlinkbutton> <StackPanel name="stackpanel_工作表选择" Visibility="Collapsed" OrIEntation="Horizontal" margin="10 0" > <TextBlock name="textblock_工作表" Text="工作表:" Foreground="Blue" VerticalAlignment="Center" ></TextBlock> <ComboBox name="comboBox_工作表选择" WIDth="25" HorizontalAlignment="left" SelectionChanged="comboBox_工作表选择_SelectionChanged" ></ComboBox> </StackPanel> </StackPanel> <sdk:DataGrID name="datagrID_显示" GrID.Row="1" MouseMove="datagrID_显示_MouseMove" ></sdk:DataGrID> <TextBlock name="textblock_status" Text="" Foreground="Blue" GrID.Row="2"></TextBlock> </GrID></navigation:Page>
// 3 实现代码
using System;using System.Collections.Generic;using System.linq;using System.Net;using System.windows;using System.windows.Controls;using System.windows.documents;using System.windows.input;using System.windows.Media;using System.windows.Media.Animation;using System.windows.Shapes;using System.windows.Navigation;using System.IO;using System.Xml.linq;using System.Collections;using System.windows.Data;using SLApplicationMadaming.VIEws.第2部分调试.MSOfficeExcel导入导出;namespace SLApplicationMadaming.VIEws.第2部分调试{ public partial class Page_MSOfficeExcel导入导出 : Page { #region "自定义" private madamingExcelXMLWorkSheetimport excel_xml_worksheet_import; #endregion public Page_MSOfficeExcel导入导出() { InitializeComponent(); } // 当用户导航到此页面时执行。 protected overrIDe voID OnNavigatedTo(NavigationEventArgs e) { } private voID Hyperlinkbutton_Click(object sender,RoutedEventArgs e) { } private voID hyperlinkbutton_导入ExcelXML文件_Click(object sender,RoutedEventArgs e) { try { OpenfileDialog ofld = new OpenfileDialog(); if (ofld.ShowDialog() == true) { string name = ofld.file.name; Stream stream = ofld.file.OpenRead(); stackpanel_工作表选择.Visibility = Visibility.Collapsed ; excel_xml_worksheet_import = new madamingExcelXMLWorkSheetimport(stream); stackpanel_工作表选择.Visibility = Visibility.Visible; comboBox_工作表选择.Items.Clear(); for (int i = 0; i < excel_xml_worksheet_import.WorkSheets.Count(); i++) { ComboBoxItem c = new ComboBoxItem(); c.Content = excel_xml_worksheet_import.WorkSheets[i].Worksheetname; comboBox_工作表选择.Items.Add(c); } if (comboBox_工作表选择.Items.Count() > 0) comboBox_工作表选择.Selectedindex = 0; } } catch (Exception ex) { MessageBox.Show(ex.Message,"打开文件提示",MessageBoxbutton.OK); } } private voID datagrID_显示_MouseMove(object sender,MouseEventArgs e) { textblock_status.Text =string.Format ("{0}",datagrID_显示.Columns.Count()); } private voID comboBox_worksheet_SelectionChanged(object sender,SelectionChangedEventArgs e) { } private voID comboBox_工作表选择_SelectionChanged(object sender,SelectionChangedEventArgs e) { int i = comboBox_工作表选择.Selectedindex; ComboBoxItem ci=(ComboBoxItem)comboBox_工作表选择.SelectedItem ; textblock_工作表.Text = string.Format("工作表:{0}",ci.Content); //excel_xml_worksheet_import.GeerateDataGrIDheaders(datagrID_显示,i); excel_xml_worksheet_import.GenerateDataGrIDData(datagrID_显示,i); } }}总结
以上是内存溢出为你收集整理的silverlight 导入Excel XML 文件全部内容,希望文章能够帮你解决silverlight 导入Excel XML 文件所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)