Advertisement
Guest User

Untitled

a guest
Mar 21st, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 12.51 KB | None | 0 0
  1. public abstract class OpenXmlReaderBase : IDisposable
  2.     {
  3.         protected const string DEFAULT_TRUE_STR = "true";
  4.         protected const string DEFAULT_FALSE_STR = "false";
  5.         protected const string DIGITAL_TRUE_STR = "1";
  6.         protected const string DIGITAL_FALSE_STR = "0";
  7.  
  8.         protected SpreadsheetDocument Doc { get; set; }
  9.         protected WorkbookPart WorkbookPart { get; set; }
  10.         protected SharedStringTablePart StringTable { get; set; }
  11.         protected Sheet[] Sheets { get; set; }
  12.         protected Sheet CurrentSheet { get; set; }
  13.         protected WorksheetPart CurrentWorksheetPart { get; set; }
  14.  
  15.         public int GetSheetsCount()
  16.         {
  17.             if (Sheets is null)
  18.                 return 0;
  19.             return Sheets.Length;
  20.         }
  21.  
  22.         public void OpenFile(string path)
  23.         {
  24.             Doc = SpreadsheetDocument.Open(path, false);
  25.             WorkbookPart = Doc.WorkbookPart;
  26.             Sheets = WorkbookPart.Workbook.Descendants<Sheet>().Where(item =>
  27.                     !(item.State != null && item.State.HasValue &&
  28.                       (item.State.Value == SheetStateValues.Hidden || item.State.Value == SheetStateValues.VeryHidden)))
  29.                 .ToArray();
  30.             StringTable = WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
  31.         }
  32.  
  33.         public string GetActiveSheetName()
  34.         {
  35.             return CurrentSheet?.Name;
  36.         }
  37.  
  38.         public abstract bool SetActiveSheet(int idx);
  39.         public abstract Row GetRow(int idx);
  40.  
  41.         public Cell FindCell(int rowId, string cellReference)
  42.         {
  43.             // получить строку
  44.             var row = GetRow(rowId);
  45.             if (row is null)
  46.                 return null;
  47.             // получить ячейку
  48.             if (!row.HasChildren)
  49.                 return null;
  50.             var cell = row.ChildElements.Where(x => (x as Cell).CellReference == cellReference).FirstOrDefault();
  51.             return (Cell)cell;
  52.         }
  53.  
  54.         public Cell FindCellInRow(int rowId, string column)
  55.         {
  56.             // получить строку
  57.             var row = GetRow(rowId);
  58.             if (row is null)
  59.                 return null;
  60.             // получить ячейку
  61.             if (!row.HasChildren)
  62.                 return null;
  63.             var cell = row.GetCell(column);
  64.             return cell;
  65.         }
  66.  
  67.         #region get cell value
  68.  
  69.         public string GetCellValueAsString(Cell cell)
  70.         {
  71.             if (null == cell)
  72.                 return string.Empty;
  73.             var value = cell.InnerText;
  74.             if (null == cell.DataType)
  75.                 return value;
  76.             switch (cell.DataType.Value)
  77.             {
  78.                 case CellValues.String:
  79.                     value = string.IsNullOrEmpty(cell.CellValue?.InnerText) ? cell.InnerText : cell.CellValue.InnerText;
  80.                     break;
  81.                 case CellValues.SharedString:
  82.                     if (StringTable != null)
  83.                         value = StringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
  84.                     break;
  85.                 case CellValues.Boolean:
  86.                     value = string.Equals(cell.InnerText, DIGITAL_TRUE_STR) ? DEFAULT_TRUE_STR : DEFAULT_FALSE_STR;
  87.                     break;
  88.             }
  89.  
  90.             return value;
  91.         }
  92.  
  93.         public bool GetCellValueAsBoolOrDefault(Cell cell)
  94.         {
  95.             if (cell.DataType.HasValue && CellValues.Boolean == cell.DataType.Value)
  96.                 return string.Equals(cell.InnerText, DIGITAL_TRUE_STR);
  97.             if (bool.TryParse(cell.InnerText, out var res))
  98.                 return res;
  99.             return !string.IsNullOrEmpty(cell.InnerText);
  100.         }
  101.  
  102.         public bool? GetCellValueAsBoolOrNull(Cell cell, string trueVal = DEFAULT_TRUE_STR)
  103.         {
  104.             if (string.IsNullOrEmpty(cell.InnerText))
  105.                 return null;
  106.             if (cell.DataType.HasValue && CellValues.Boolean == cell.DataType.Value)
  107.                 return string.Equals(cell.InnerText, DIGITAL_TRUE_STR);
  108.             return string.Equals(cell.InnerText, trueVal);
  109.         }
  110.  
  111.         public double GetCellValueAsDoubleOrDefault(Cell cell)
  112.         {
  113.             var valStr = string.IsNullOrEmpty(cell.CellValue?.InnerText) ? cell.InnerText : cell.CellValue.InnerText;
  114.             double.TryParse(valStr, NumberStyles.Any, CultureInfo.InvariantCulture, out var result);
  115.             return result;
  116.         }
  117.  
  118.         public double? GetCellValueAsDoubleOrNull(Cell cell)
  119.         {
  120.             if (string.IsNullOrEmpty(cell.InnerText))
  121.                 return null;
  122.             return GetCellValueAsDoubleOrDefault(cell);
  123.         }
  124.  
  125.         public decimal GetCellValueAsDecimalOrDefault(Cell cell)
  126.         {
  127.             decimal.TryParse(cell.InnerText, NumberStyles.Any, CultureInfo.InvariantCulture, out var result);
  128.             return result;
  129.         }
  130.  
  131.         public decimal? GetCellValueAsDecimalOrNull(Cell cell)
  132.         {
  133.             if (string.IsNullOrEmpty(cell.InnerText))
  134.                 return null;
  135.             return GetCellValueAsDecimalOrDefault(cell);
  136.         }
  137.  
  138.         public long GetCellValueAsLongOrDefault(Cell cell)
  139.         {
  140.             var result = GetCellValueAsDecimalOrDefault(cell);
  141.             return (long)result;
  142.         }
  143.  
  144.         public long? GetCellValueAsLongOrNull(Cell cell)
  145.         {
  146.             if (cell == null || string.IsNullOrEmpty(cell.InnerText))
  147.                 return null;
  148.             return (long)GetCellValueAsDecimalOrDefault(cell);
  149.         }
  150.  
  151.         public DateTime GetCellValueAsDateTimeOrDefault(Cell cell)
  152.         {
  153.             var days = GetCellValueAsDoubleOrDefault(cell);
  154.             return CalculateDateTimeFromDaysFromEpoch(days);
  155.         }
  156.  
  157.         public DateTime? GetCellValueAsDateTimeOrNull(Cell cell)
  158.         {
  159.             if (string.IsNullOrEmpty(cell.InnerText))
  160.                 return null;
  161.             return GetCellValueAsDateTimeOrDefault(cell);
  162.         }
  163.  
  164.         #endregion
  165.  
  166.         private DateTime CalculateDateTimeFromDaysFromEpoch(double days)
  167.         {
  168.             // Microsoft Excel for Windows uses 1 Jan 1900 as the epoch
  169.             // Microsoft Excel for Macintosh uses 1 Jan 1904 as the epoch
  170.             var for1904Epoch = WorkbookPart.Workbook.WorkbookProperties.Date1904;
  171.             if (for1904Epoch is null)
  172.                 for1904Epoch = false;
  173.             var dtEpoch = for1904Epoch ? Epoch1904 : Epoch1900;
  174.  
  175.             DateTime dt;
  176.  
  177.             if (for1904Epoch)
  178.                 dt = dtEpoch.AddDays(days);
  179.             else
  180.                 dt = days < 59 ? dtEpoch.AddDays(days - 1.0) : dt = dtEpoch.AddDays(days - 2.0);
  181.  
  182.             return dt;
  183.         }
  184.  
  185.         private static readonly DateTime Epoch1900 = new DateTime(1900, 1, 1);
  186.         private static readonly DateTime Epoch1904 = new DateTime(1904, 1, 1);
  187.  
  188.         #region IDisposable Support
  189.  
  190.         private bool disposedValue; // To detect redundant calls
  191.  
  192.         protected virtual void Dispose(bool disposing)
  193.         {
  194.             if (!disposedValue)
  195.             {
  196.                 if (disposing)
  197.                     if (null != Doc)
  198.                     {
  199.                         Doc.Close();
  200.                         Doc.Dispose();
  201.                     }
  202.  
  203.                 Doc = null;
  204.                 disposedValue = true;
  205.             }
  206.         }
  207.  
  208.         // This code added to correctly implement the disposable pattern.
  209.         public void Dispose()
  210.         {
  211.             // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
  212.             Dispose(true);
  213.         }
  214.  
  215.         #endregion
  216.     }
  217.  
  218.     public class ExcelReader : OpenXmlReaderBase
  219.     {
  220.         protected const string DEFAULT_TRUE_STR = "true";
  221.         protected const string DEFAULT_FALSE_STR = "false";
  222.         protected const string DIGITAL_TRUE_STR = "1";
  223.         protected const string DIGITAL_FALSE_STR = "0";
  224.  
  225.         public int RowsCount
  226.         {
  227.             get
  228.             {
  229.                 if (rowsCount == -1) rowsCount = GetAllRows().Count;
  230.                 rowsCount = GetAllRows().Count;
  231.                 return rowsCount;
  232.             }
  233.         }
  234.  
  235.  
  236.  
  237.         private int rowsCount = -1;
  238.  
  239.  
  240.         public void OpenFile(Stream stream)
  241.         {
  242.             Doc = SpreadsheetDocument.Open(stream, false);
  243.             WorkbookPart = Doc.WorkbookPart;
  244.             Sheets = WorkbookPart.Workbook.Descendants<Sheet>().Where(item =>
  245.                     !(item.State != null && item.State.HasValue &&
  246.                       (item.State.Value == SheetStateValues.Hidden || item.State.Value == SheetStateValues.VeryHidden)))
  247.                 .ToArray();
  248.             StringTable = WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
  249.         }
  250.  
  251.         public void OpenFile(String path)
  252.         {
  253.             Doc = SpreadsheetDocument.Open(path, false);
  254.             WorkbookPart = Doc.WorkbookPart;
  255.             Sheets = WorkbookPart.Workbook.Descendants<Sheet>().Where(item =>
  256.                     !(item.State != null && item.State.HasValue &&
  257.                       (item.State.Value == SheetStateValues.Hidden || item.State.Value == SheetStateValues.VeryHidden)))
  258.                 .ToArray();
  259.             StringTable = WorkbookPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
  260.         }
  261.  
  262.         private static readonly Type ROW_TYPE = typeof(Row);
  263.  
  264.  
  265.         public override Row GetRow(int idx)
  266.         {
  267.             var idxStr = idx.ToString();
  268.             //var stream = CurrentWorksheetPart.GetStream();
  269.  
  270.             using (var reader = OpenXmlReader.Create(CurrentWorksheetPart))
  271.             {
  272.                 while (reader.Read())
  273.                     if (ROW_TYPE == reader.ElementType)
  274.                     {
  275.                         do
  276.                         {
  277.                             var rowNum = reader.Attributes.First(a => a.LocalName == "r").Value;
  278.                             if (string.Equals(idxStr, rowNum))
  279.                             {
  280.                                 var row = reader.LoadCurrentElement() as Row;
  281.                                 return row;
  282.                             }
  283.                         } while (reader.ReadNextSibling());
  284.  
  285.                         break;
  286.                     }
  287.  
  288.                 reader.Close();
  289.             }
  290.  
  291.             return null;
  292.         }
  293.  
  294.         public List<Row> GetAllRows()
  295.         {
  296.             var rows = new List<Row>();
  297.  
  298.             using (var reader = OpenXmlReader.Create(CurrentWorksheetPart))
  299.             {
  300.                 while (reader.Read())
  301.                     if (ROW_TYPE == reader.ElementType)
  302.                     {
  303.                         do
  304.                         {
  305.                             var rowNum = reader.Attributes.First(a => a.LocalName == "r").Value;
  306.  
  307.                             rows.Add(reader.LoadCurrentElement() as Row);
  308.                         } while (reader.ReadNextSibling());
  309.  
  310.                         break;
  311.                     }
  312.  
  313.                 reader.Close();
  314.             }
  315.  
  316.             return rows;
  317.         }
  318.  
  319.         public Row GetFirstRow()
  320.         {
  321.             using (var reader = OpenXmlReader.Create(CurrentWorksheetPart))
  322.             {
  323.                 while (reader.Read())
  324.                     if (ROW_TYPE == reader.ElementType)
  325.                         return reader.LoadCurrentElement() as Row;
  326.             }
  327.  
  328.             return null;
  329.         }
  330.  
  331.         public override bool SetActiveSheet(int idx)
  332.         {
  333.             if (Sheets is null || Sheets.Length <= idx)
  334.                 return false;
  335.             CurrentSheet = Sheets[idx];
  336.             CurrentWorksheetPart = (WorksheetPart)WorkbookPart.GetPartById(CurrentSheet.Id);
  337.             return true;
  338.         }
  339.     }
  340.  
  341.     public static class RowExtention
  342.     {
  343.         public static Cell GetCell(this Row row, string clmnRef)
  344.         {
  345.             if (!row.HasChildren)
  346.                 return null;
  347.             var cellRef = clmnRef + row.RowIndex;
  348.             var cell = row.ChildElements.Where(x => (x as Cell).CellReference == cellRef).FirstOrDefault();
  349.             return (Cell)cell;
  350.         }
  351.  
  352.         public static Cell GetCellByRef(this Row row, string cellRef)
  353.         {
  354.             if (!row.HasChildren)
  355.                 return null;
  356.  
  357.             var cell = row.ChildElements.Where(x => (x as Cell).CellReference == cellRef).FirstOrDefault();
  358.             return (Cell)cell;
  359.         }
  360.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement