110,502
社区成员
发帖
与我相关
我的任务
分享
public static List<T> Import<T>(string filePath)
{
List<T> rst = new List<T>();
System.Type t = typeof(T);
ExcelAttribute excAttr = t.GetCustomAttribute<ExcelAttribute>(false);
List<ProperyColumnAttributes> propAttrs = new List<ProperyColumnAttributes>();
foreach (var prop in t.GetProperties())
{
ExcelColumnAttribute attr = prop.GetCustomAttribute<ExcelColumnAttribute>(false);
if (attr != null) propAttrs.Add(new ProperyColumnAttributes { Attribute = attr, Property = prop });
}
using (FileStream fs = File.OpenRead(filePath))
{
IWorkbook workBook = null;
if (filePath.IndexOf(".xlsx") > 0)
workBook = new XSSFWorkbook(fs); // 2007版本
else if (filePath.IndexOf(".xls") > 0) // 2003版本
workBook = new HSSFWorkbook(fs);
else
{
try { workBook = new XSSFWorkbook(fs); } catch { }
if (workBook == null)
workBook = new HSSFWorkbook(fs);
}
ISheet sheet;
你是想用这种反射吗?传入一个类,通过特性灵活获取excel的信息,不用为每一种款式的excel编写代码
void Main()
{
string fileName = @"c:\path\to\my\file.xlsx";
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, false))
{
WorkbookPart workbookPart = doc.WorkbookPart;
SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
SharedStringTable sst = sstpart.SharedStringTable;
WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
Worksheet sheet = worksheetPart.Worksheet;
var cells = sheet.Descendants<Cell>();
var rows = sheet.Descendants<Row>();
Console.WriteLine("Row count = {0}", rows.LongCount());
Console.WriteLine("Cell count = {0}", cells.LongCount());
// One way: go through each cell in the sheet
foreach (Cell cell in cells)
{
if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
{
int ssid = int.Parse(cell.CellValue.Text);
string str = sst.ChildElements[ssid].InnerText;
Console.WriteLine("Shared string {0}: {1}", ssid, str);
}
else if (cell.CellValue != null)
{
Console.WriteLine("Cell contents: {0}", cell.CellValue.Text);
}
}
// Or... via each row
foreach (Row row in rows)
{
foreach (Cell c in row.Elements<Cell>())
{
if ((c.DataType != null) && (c.DataType == CellValues.SharedString))
{
int ssid = int.Parse(c.CellValue.Text);
string str = sst.ChildElements[ssid].InnerText;
Console.WriteLine("Shared string {0}: {1}", ssid, str);
}
else if (c.CellValue != null)
{
Console.WriteLine("Cell contents: {0}", c.CellValue.Text);
}
}
}
}
}
}