OpenXml 2.0 读取Excel
Excel 单元格中的数据类型包括7种:
Boolean、Date、Error、InlineString、Number、SharedString、String
读取源代码:
1 List<string> returnList = new List<string>(); 2 using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false)) 3 { 4 foreach (Sheet sheet in spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>()) 5 { 6 returnList.Add(sheet.Name); 7 } 8 9 foreach (Sheet sheet in spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>()) 10 { 11 IEnumerable<Sheet> IEnumerableSheet = spreadsheetDocument.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheet.Name); 12 WorksheetPart worksheetPart = (WorksheetPart)spreadsheetDocument.WorkbookPart.GetPartById(IEnumerableSheet.First().Id); 13 IEnumerable<Row> rows = worksheetPart.Worksheet.Descendants<Row>(); 14 SharedStringTable sharedStringTable = spreadsheetDocument.WorkbookPart.SharedStringTablePart.SharedStringTable; 15 foreach (Row row in rows) 16 { 17 foreach (Cell cell in row.Descendants<Cell>()) 18 { 19 if (cell.ChildElements.Count == 0) 20 { 21 22 } 23 else 24 { 25 if (cell.DataType != null) 26 { 27 //获取其中共享数据类型 28 if (cell.DataType.Value == CellValues.SharedString) 29 { 30 string cellValue = sharedStringTable.ChildElements[int.Parse(cell.CellValue.InnerText)].InnerText; 31 returnList.Add(cellValue); 32 } 33 } 34 } 35 36 } 37 } 38 } 39 return returnList; 40 }
其中Bool类型数据0会处理为False 1处理成True;
其中最不好处理的数据就是时间Date;
因为工作需要,目前只处理共享数据