Я очень доволен SpreadsheetLight.Однако я не могу не думать, что я что-то упустил.В Excel вы можете «Форматировать таблицу», а затем, когда таблица выбрана, появляется вкладка «Инструменты таблицы - Дизайн».Вы можете изменить отличное имя таблицы.
Однако я изо всех сил пытался найти прямой способ использования SpreadsheetLight для загрузки файла Excel, а затем получить таблицы на листе.
НетДругой способ, кроме обращения к размышлению?
using SpreadsheetLight;
~~~~~~~
~~~~~~~
~~~~~~~
public DataTable LoadExcelFileTable(string FullFileName)
{
//Load Excel File, get Table Names, compare, Load matching table name into DataTable and return.
string tableName = "Table1";
SLDocument sl = new SLDocument(FullFileName);
sl.SelectWorksheet(SLDocument.DefaultFirstSheetName);
DataTable excelTableDT = GetExcelTablesOfSelectedWorksheet(sl);
//Using table dt can extract data....
return null; //Placeholder for now
}
private DataTable GetExcelTablesOfSelectedWorksheet(SLDocument sl)
{
string sci = "StartColumnIndex";
string sri = "StartRowIndex";
string eci = "EndColumnIndex";
string eri = "EndRowIndex";
DataTable excelTableDT = new DataTable();
excelTableDT.Columns.Add("DisplayName");
excelTableDT.Columns.Add(sci, typeof(int)); // 1 == A, 2 == B
excelTableDT.Columns.Add(sri, typeof(int)); // 1 == 1, 2 == 2
excelTableDT.Columns.Add(eci, typeof(int)); // 1 == A, 2 == B
excelTableDT.Columns.Add(eri, typeof(int)); // 1 == 1, 2 == 2
//Appears it's not made public, we cannot normally access tables and then by name determine start and end cells.
//Reflection to the rescue
FieldInfo slwsFieldInfo = typeof(SLDocument).GetField("slws", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (slwsFieldInfo != null)
{
var b = slwsFieldInfo.GetValue(sl);
if (b != null)
{
var TablesPropInfo = b.GetType().GetProperty("Tables", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (TablesPropInfo != null)
{
var oTables = TablesPropInfo.GetValue(b);
if (oTables != null && oTables is List<SLTable> Tables)
{
if (Tables != null)
{
foreach (SLTable slTable in Tables)
{
//Get the info we need
string DisplayName = slTable.DisplayName;
int StartColumnIndex = Reflection_TryGetIntPropertyValue(slTable, sci);
int StartRowIndex = Reflection_TryGetIntPropertyValue(slTable, sri);
int EndColumnIndex = Reflection_TryGetIntPropertyValue(slTable, eci);
int EndRowIndex = Reflection_TryGetIntPropertyValue(slTable, eri);
//Add to DataTable
excelTableDT.Rows.Add(new object[] { DisplayName, StartColumnIndex, StartRowIndex, EndColumnIndex, EndRowIndex });
}
}
}
}
}
}
return excelTableDT;
}
private int Reflection_TryGetIntPropertyValue(object o, string propertyName)
{
int x = -1;
try
{
var propInfo = o.GetType().GetProperty(propertyName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
if (propInfo != null)
{
object val = propInfo.GetValue(o);
if (val != null && val is int yay)
{
x = yay;
}
}
}
catch { }
return x;
}