base commit

main
syneffort 1 year ago
parent 1ebecdff62
commit ff51117201
  1. 25
      ExcelHelper/ExcelHelper.sln
  2. 115
      ExcelHelper/ExcelHelper/ExcelHelper.cs
  3. 13
      ExcelHelper/ExcelHelper/ExcelHelper.csproj

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34511.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExcelHelper", "ExcelHelper\ExcelHelper.csproj", "{A27BBD28-F1A8-46D6-90E7-7026B6DA54BA}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A27BBD28-F1A8-46D6-90E7-7026B6DA54BA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A27BBD28-F1A8-46D6-90E7-7026B6DA54BA}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A27BBD28-F1A8-46D6-90E7-7026B6DA54BA}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A27BBD28-F1A8-46D6-90E7-7026B6DA54BA}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {57173180-D546-4DCE-8829-F7A664D607CF}
EndGlobalSection
EndGlobal

@ -0,0 +1,115 @@
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System.Text;
using System.Text.RegularExpressions;
namespace ExcelHelper
{
public class ExcelHelper
{
private static readonly ExcelHelper _instance = new ExcelHelper();
public static ExcelHelper Instance { get { return _instance; } }
/// <summary>
/// Get excel data
/// </summary>
/// <param name="sourcePath">excel path</param>
/// <param name="sheetName">sheet name</param>
/// <param name="rowStartPosition">row start position (first row = 1)</param>
/// <param name="tempPath">copy path</param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public List<Dictionary<string, string>> GetData(string sourcePath, string sheetName, bool removeHeader, int rowStartPosition = 1, string tempPath = "./temp_file.xlsx")
{
File.Copy(sourcePath, tempPath, true);
List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
StringBuilder sb = new StringBuilder();
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(tempPath, true))
{
WorkbookPart workbookPart = doc.WorkbookPart;
Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
if (sheet == null)
throw new Exception("Cannot find sheet.");
WorksheetPart worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
Worksheet worksheet = worksheetPart.Worksheet;
List<Row> rows = worksheet.Descendants<Row>().Where(r => r.RowIndex >= rowStartPosition).ToList();
if (removeHeader)
rows.RemoveAt(0);
for (int i = 0; i < rows.Count; i++)
{
Dictionary<string, string> rowPairs = RowToKeyValuePairs(rows[i], workbookPart);
if (rowPairs == null || rowPairs.Count < 1)
continue;
data.Add(rowPairs);
}
}
return data;
}
private Dictionary<string, string> RowToKeyValuePairs(Row row, WorkbookPart workbookPart)
{
Dictionary<string, string> pairs = new Dictionary<string, string>();
var cells = row.Elements<Cell>().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<SharedStringItem>().ElementAt(sharedStringId).InnerText;
}
pairs.Add(columnName, cellValue);
}
return pairs;
}
private string ConvertValue(Dictionary<string, string> pairs, string key)
{
if (!pairs.ContainsKey(key))
return null;
return pairs[key];
}
private T ConvertValue<T>(Dictionary<string, string> pairs, string key, Func<string, T> func)
{
if (!pairs.ContainsKey(key) || func == null)
return default(T);
string value = pairs[key];
return func(value);
}
private DateTime? ConvertValueToDateTime(Dictionary<string, string> pairs, string key)
{
return ConvertValue<DateTime?>(pairs, key, x =>
{
if (string.IsNullOrEmpty(x))
return null;
if (double.TryParse(x, out double d))
return DateTime.FromOADate(d);
else
return null;
});
}
}
}

@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="3.0.1" />
</ItemGroup>
</Project>
Loading…
Cancel
Save