using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace ExcelHelperFW
{
public class ExcelHelper
{
private static readonly ExcelHelper _instance = new ExcelHelper();
public static ExcelHelper Instance { get { return _instance; } }
///
/// Get excel data
///
/// excel path
/// sheet name
/// row start position (first row = 1)
/// copy path
///
///
public List> GetData(string sourcePath, string sheetName, bool removeHeader, int rowStartPosition = 1, Func, bool> continueFunc = null, string tempPath = "./temp_file.xlsx")
{
File.Copy(sourcePath, tempPath, true);
List> data = new List>();
StringBuilder sb = new StringBuilder();
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(tempPath, true))
{
WorkbookPart workbookPart = doc.WorkbookPart;
Sheet sheet = workbookPart.Workbook.Descendants().FirstOrDefault(s => s.Name == sheetName);
if (sheet == null)
throw new Exception($"Cannot find sheet. (Sheet name: {sheetName})");
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet;
List rows = worksheet.Descendants().Where(r => r.RowIndex >= rowStartPosition).ToList();
if (removeHeader)
rows.RemoveAt(0);
for (int i = 0; i < rows.Count; i++)
{
Dictionary rowPairs = RowToKeyValuePairs(rows[i], workbookPart);
if (rowPairs == null || rowPairs.Count < 1)
continue;
if (continueFunc != null && continueFunc(rowPairs))
continue;
data.Add(rowPairs);
}
}
return data;
}
private Dictionary RowToKeyValuePairs(Row row, WorkbookPart workbookPart)
{
Dictionary pairs = new Dictionary();
var cells = row.Elements().ToList();
for (int col = 0; col < cells.Count; col++)
{
Cell cell = cells[col];
string cellReference = cell.CellReference.Value;
string columnName = Regex.Replace(cellReference, @"\d", "");
//int rowNumber = int.Parse(Regex.Replace(cellReference, "[^0-9]", ""));
string cellValue = cell.CellValue?.InnerText;
if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
{
int.TryParse(cellValue, out int sharedStringId);
cellValue = workbookPart.SharedStringTablePart.SharedStringTable.Elements().ElementAt(sharedStringId).InnerText;
}
pairs.Add(columnName, cellValue);
}
return pairs;
}
public string ConvertValue(Dictionary pairs, string key)
{
if (!pairs.ContainsKey(key))
return null;
return pairs[key];
}
public T ConvertValue(Dictionary pairs, string key, Func func)
{
if (!pairs.ContainsKey(key) || func == null)
return default(T);
string value = pairs[key];
return func(value);
}
public DateTime? ConvertValueToDateTime(Dictionary pairs, string key)
{
return ConvertValue(pairs, key, x =>
{
if (string.IsNullOrEmpty(x))
return null;
if (double.TryParse(x, out double d))
return DateTime.FromOADate(d);
else
return null;
});
}
}
}
|