我正在使用Visual Studio 2008,我需要DataTable
使用Open XML SDK 2.0从Excel工作表创建一个.我需要使用带有工作表第一行的DataTable列创建它,并使用其余值完成它.
有没有人有一个示例代码或链接可以帮助我这样做?
我认为这应该做你所要求的.如果您有共享字符串,那么另一个函数就是处理,我假设您在列标题中执行此操作.不确定这是完美的,但我希望它有所帮助.
static void Main(string[] args) { DataTable dt = new DataTable(); using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(@"..\..\example.xlsx", false)) { WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart; IEnumerablesheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild ().Elements (); string relationshipId = sheets.First().Id.Value; WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId); Worksheet workSheet = worksheetPart.Worksheet; SheetData sheetData = workSheet.GetFirstChild (); IEnumerable rows = sheetData.Descendants
(); foreach (Cell cell in rows.ElementAt(0)) { dt.Columns.Add(GetCellValue(spreadSheetDocument, cell)); } foreach (Row row in rows) //this will also include your header row... { DataRow tempRow = dt.NewRow(); for (int i = 0; i < row.Descendants
().Count(); i++) { tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants | ().ElementAt(i-1)); } dt.Rows.Add(tempRow); } } dt.Rows.RemoveAt(0); //...so i'm taking it out here. } public static string GetCellValue(SpreadsheetDocument document, Cell cell) { SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart; string value = cell.CellValue.InnerXml; if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString) { return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText; } else { return value; } } |
嗨以上代码工作正常,除了一个更改
替换下面的代码行
tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants().ElementAt(i-1)); |
同
tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants().ElementAt(i)); |
如果使用(i-1),它将抛出异常:
specified argument was out of the range of valid values. parameter name index.