using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Spreadsheet; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; namespace Tools { /// <summary> /// /// </summary> public class ExcelOpenXml { /* * excel 对象结构 * SpreadsheetDocument * 》WorkbookPart * 》WorksheetPart * 》Worksheet * 》SheetData * 》WorksheetPart * 》Worksheet * 》SheetData1 * 》Workbook * 》Sheets * 》Sheet */ public static void Create(string filename, DataSet ds) { SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook); WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart(); Workbook workbook = new Workbook(); Sheets sheets = new Sheets(); #region 创建多个 sheet 页 //创建多个sheet for (int s = 0; s < ds.Tables.Count; s++) { DataTable dt = ds.Tables[s]; var tname = dt.TableName; WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>(); Worksheet worksheet = new Worksheet(); SheetData sheetData = new SheetData(); //Page Create sheet Sheet sheet = new new Sheet () { // page associated WorksheetPart Id = spreadsheetDocument.WorkbookPart.GetIdOfPart (worksheetPart), SheetId = UInt32Value.FromUInt32 (( uint ) + S . 1 ), the Name = tname }; sheets.Append (sheet); #region create sheet row row row; uint rowIndex = . 1 ; // add header row = new new Row() { RowIndex = UInt32Value.FromUInt32(rowIndex++) }; sheetData.Append(row); for (int i = 0; i < dt.Columns.Count; i++) { Cell newCell = new Cell(); newCell.CellValue = new CellValue(dt.Columns[i].ColumnName); newCell.DataType = new EnumValue<CellValues>(CellValues.String); row.Append(newCell); } //添加内容 object val = null; for (int i = 0; i < dt.Rows.Count; i++) { row = new Row() { RowIndex = UInt32Value.FromUInt32(rowIndex++) }; sheetData.Append(row); for (int j = 0; j < dt.Columns.Count; j++) { Cell newCell = new Cell(); val = dt.Rows[i][j]; newCell.CellValue = new CellValue(val.ToString()); newCell.DataType = new EnumValue<CellValues>(CellValues.String); row.Append(newCell); } } #endregion worksheet.Append(sheetData); worksheetPart.Worksheet = worksheet; worksheetPart.Worksheet.Save(); } #endregion workbook.Append(sheets); workbookpart.Workbook = workbook; workbookpart.Workbook.Save(); spreadsheetDocument.Close(); } public static DataTable GetSheet(string filename, string sheetName) { DataTable dt = new DataTable(); using (SpreadsheetDocument document = SpreadsheetDocument.Open(filename, false)) { WorkbookPart wbPart = document.WorkbookPart; //Find sheet by sheet page name Sheet sheet = wbPart .Workbook .Descendants <Sheet> () .Where (S => == s.Name sheetName) .FirstOrDefault (); IF (sheet == null ) { the throw new new ArgumentException The ( " Could not find " + sheetName + " sheet page " ); } // get shared Excel table SharedStringTablePart sharedStringTablePart = wbPart .GetPartsOfType <SharedStringTablePart> () .FirstOrDefault (); SharedStringTable sharedStringTable = null ; IF (sharedStringTablePart =! Null ) sharedStringTable = sharedStringTablePart.SharedStringTable; #region Construction DataTable // add talbe columns, the number of columns returned Func <Row, int > addTabColumn = (R & lt) => { // iterate cell the foreach (the cell C in r.Elements <the cell> ()) { dt.Columns.Add(GetCellVal(c, sharedStringTable)); } return dt.Columns.Count; }; //添加行 Action<Row> addTabRow = (r) => { DataRow dr = dt.NewRow(); int colIndex = 0; int colCount = dt.Columns.Count; //遍历单元格 foreach (Cell c in r.Elements<Cell>()) { if (colIndex >= colCount) break; dr[colIndex++] = GetCellVal(c, sharedStringTable); } dt.Rows.Add(dr); }; #endregion //通过 sheet.id 查找 WorksheetPart WorksheetPart worksheetPart = wbPart.GetPartById(sheet.Id) as WorksheetPart; //查找 sheetdata SheetData sheetData = worksheetPart.Worksheet.Elements<SheetData>().First(); //遍历行 foreach (Row r in sheetData.Elements<Row>()) { // build table column IF (r.RowIndex == . 1 ) { addTabColumn (R & lt); Continue ; } // build table row addTabRow (R & lt); } } return dt; } /// <Summary> / // get a cell value /// </ Summary> /// <param name = "cell"> </ param> /// <param name = "sharedStringTable"> </ param> /// <Returns> < / returns> static string GetCellVal(Cell cell, SharedStringTable sharedStringTable) { var val = cell.InnerText; if (cell.DataType != null) { switch (cell.DataType.Value) { //从共享表中获取值 case CellValues.SharedString: if (sharedStringTable != null) val = sharedStringTable .ElementAt(int.Parse(val)) .InnerText; break; default: val = string.Empty; break; } } return val; } public static DataSet ConvertToDataSet<T>(IList<T> list) { if (list == null || list.Count <= 0) { return null; } DataSet ds = new DataSet(); DataTable dt = new DataTable(typeof(T).Name); DataColumn column; DataRow row; System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); foreach (T t in list) { if (t == null) { continue; } row = dt.NewRow(); for (int i = 0, j = myPropertyInfo.Length; i < j; i++) { System.Reflection.PropertyInfo pi = myPropertyInfo[i]; string name = pi.Name; if (dt.Columns[name] == null) { var type = pi.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = type.GetGenericArguments()[0]; } column = new new DataColumn(name, type); dt.Columns.Add (column); } Row [name] = pi.GetValue (T, null ); } dt.Rows.Add (Row); } ds.Tables.Add (dt); return DS; } public static List <T> ConvertToList <T> (the DataTable dt) WHERE T: new new () { // definition of a set of List <T> TS = new new List <T> (); // get the type of the model Type = type typeof (T); // define a temporary variable String TempName = "" ; // iterate through all the data rows in datatable the foreach (the DataRow DR in dt.Rows) { T T = new new T (); // get the public properties model PropertyInfo [] = the propertys t.GetType () GetProperties ();. // iterate through all attributes the foreach (PI PropertyInfo in the propertys) { // this attribute is assigned to a temporary variable TempName = pi.Name; // check the column contains datatable IF (dt.Columns.Contains (TempName)) { // determines whether the attribute has the setter, it means that what is our physical layer {get; set;} If we have a set of entity method, you can assign it shows! IF (! pi.CanWrite) Continue ; { // Value Object value = DR [TempName]; IF (! = value DBNull.Value) pi.SetValue (T, value, null ); } } } // objects to generic collection ts.Add (T); } return TS; } } }
[Excel] OpenXml import and export
Guess you like
Origin www.cnblogs.com/xuxml/p/12040165.html
Recommended
Ranking