如何使用OpenXMLAPI从Excel电子表格中读取表格?

如何使用OpenXMLAPI从Excel电子表格中读取表格?,excel,api,openxml,spreadsheetml,Excel,Api,Openxml,Spreadsheetml,我在网上读了很多关于如何使用OpenXMLAPI获取细胞数据的文章。但实际上没有什么特别直接的东西。大多数似乎都是写在SpreadsheetML上,而不是阅读。。。但即使这样也没有多大帮助。 我有一个电子表格,里面有一张表格。我知道表名是什么,我可以找出它在哪张表上,以及表中有哪些列。但我不知道如何获取包含表中数据的行集合 我使用以下命令加载文档并获取工作簿的句柄: SpreadsheetDocument document = SpreadsheetDocument.Open("file.xls

我在网上读了很多关于如何使用OpenXMLAPI获取细胞数据的文章。但实际上没有什么特别直接的东西。大多数似乎都是写在SpreadsheetML上,而不是阅读。。。但即使这样也没有多大帮助。 我有一个电子表格,里面有一张表格。我知道表名是什么,我可以找出它在哪张表上,以及表中有哪些列。但我不知道如何获取包含表中数据的行集合

我使用以下命令加载文档并获取工作簿的句柄:

SpreadsheetDocument document = SpreadsheetDocument.Open("file.xlsx", false);
WorkbookPart workbook = document.WorkbookPart;
我要找到这张桌子/床单:

Table table = null;
foreach (Sheet sheet in workbook.Workbook.GetFirstChild<Sheets>())
{
    WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheet.Id);
    foreach (TableDefinitionPart tableDefinitionPart in worksheetPart.TableDefinitionParts)
    {
        if (tableDefinitionPart.Table.DisplayName == this._tableName)
        {
            table = tableDefinitionPart.Table;
            break;
        }
    }
}
Table Table=null;
foreach(工作簿.工作簿.GetFirstChild()中的工作表)
{
工作表部件工作表部件=(工作表部件)document.WorkbookPart.GetPartById(sheet.Id);
foreach(工作表中的TableDefinitionPart TableDefinitionPart部分TableDefinitionParts)
{
if(tableDefinitionPart.Table.DisplayName==此.\u tableName)
{
table=tableDefinitionPart.table;
打破
}
}
}

我可以通过搜索table.TableColumns来迭代表中的列。

使用OpenXMLAPI阅读Excel 2007/2010电子表格非常容易。在某种程度上甚至比使用OleDB更简单,就像我们一直使用的快速脏解决方案一样。此外,它不仅简单而且冗长,我认为如果必须对其进行注释和解释,那么将所有代码放在这里是没有用的,因此我将只写一个摘要,并链接一篇好文章。阅读,它解释了如何以一种非常简单的方式阅读XLSX文档

总结一下,您将执行以下操作:

  • 使用
    电子表格文档打开
    电子表格文档
    。打开
  • 从文档的
    WorkbookPart
    通过LINQ查询获取所需的
    工作表
  • 使用
    工作表的Id(最后!)获取
    工作表部分
    (您需要的对象)
在代码中,剥离注释和错误处理:

using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, false))
{
   Sheet sheet = document.WorkbookPart.Workbook
      .Descendants<Sheet>()
      .Where(s => s.Name == sheetName)
      .FirstOrDefault();

   WorksheetPart sheetPart = 
      (WorksheetPart)(document.WorkbookPart.GetPartById(theSheet.Id));
}
现在,您可以询问所有行和单元格:

foreach (Row row in sheetData.Elements<Row>())
{
   foreach (Cell cell in row.Elements<Cell>())
   {
      string text = cell.CellValue.Text;
      // Do something with the cell value
   }
}
foreach(sheetData.Elements()中的行)
{
foreach(row.Elements()中的单元格)
{
字符串文本=cell.CellValue.text;
//用单元格值做些什么
}
}
要简单地枚举普通电子表格,您可以使用
工作表部件
对象的
子体()


如果您需要更多关于OpenXML的资源,请看一看,它包含了很多很好的教程。

可能有很多更好的方法来编写它,但是我把它拼凑起来,因为我需要它,所以希望它能帮助其他人

using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;

    private static DataTable genericExcelTable(FileInfo fileName)
    {
        DataTable dataTable = new DataTable();
        try
        {
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fileName.FullName, false))
            {
                Workbook wkb = doc.WorkbookPart.Workbook;
                Sheet wks = wkb.Descendants<Sheet>().FirstOrDefault();
                SharedStringTable sst = wkb.WorkbookPart.SharedStringTablePart.SharedStringTable;
                List<SharedStringItem> allSSI = sst.Descendants<SharedStringItem>().ToList<SharedStringItem>();
                WorksheetPart wksp = (WorksheetPart)doc.WorkbookPart.GetPartById(wks.Id);

                foreach (TableDefinitionPart tdp in wksp.TableDefinitionParts)
                {
                    QueryTablePart qtp = tdp.QueryTableParts.FirstOrDefault<QueryTablePart>();
                    Table excelTable = tdp.Table;
                    int colcounter = 0;
                    foreach (TableColumn col in excelTable.TableColumns)
                    {
                        DataColumn dcol = dataTable.Columns.Add(col.Name);
                        dcol.SetOrdinal(colcounter);
                        colcounter++;
                    }

                    SheetData data = wksp.Worksheet.Elements<SheetData>().First();

                    foreach (DocumentFormat.OpenXml.Spreadsheet.Row row in data)
                    {
                        if (isInTable(row.Descendants<Cell>().FirstOrDefault(), excelTable.Reference, true))
                        {
                            int cellcount = 0;
                            DataRow dataRow = dataTable.NewRow();
                            foreach (Cell cell in row.Elements<Cell>())
                            {

                                if (cell.DataType != null && cell.DataType.InnerText == "s")
                                {
                                    dataRow[cellcount] = allSSI[int.Parse(cell.CellValue.InnerText)].InnerText;
                                }
                                else
                                {
                                    dataRow[cellcount] = cell.CellValue.Text;
                                }
                                cellcount++;
                            }
                            dataTable.Rows.Add(dataRow);
                        }
                    }
                }
            }
            //do whatever you want with the DataTable
            return dataTable;
        }
        catch (Exception ex)
        {
            //handle an error
            return dataTable;
        }
    }
    private static Tuple<int, int> returnCellReference(string cellRef)
    {
        int startIndex = cellRef.IndexOfAny("0123456789".ToCharArray());
        string column = cellRef.Substring(0, startIndex);
        int row = Int32.Parse(cellRef.Substring(startIndex));
        return new Tuple<int,int>(TextToNumber(column), row);
    }
    private static int TextToNumber(string text)
    {
        return text
            .Select(c => c - 'A' + 1)
            .Aggregate((sum, next) => sum * 26 + next);
    }
    private static bool isInTable(Cell testCell, string tableRef, bool headerRow){
        Tuple<int, int> cellRef = returnCellReference(testCell.CellReference.ToString());
        if (tableRef.Contains(":"))
        {
            int header = 0;
            if (headerRow)
            {
                header = 1;
            }
            string[] tableExtremes = tableRef.Split(':');
            Tuple<int, int> startCell = returnCellReference(tableExtremes[0]);
            Tuple<int, int> endCell = returnCellReference(tableExtremes[1]);
            if (cellRef.Item1 >= startCell.Item1
                && cellRef.Item1 <= endCell.Item1
                && cellRef.Item2 >= startCell.Item2 + header
                && cellRef.Item2 <= endCell.Item2) { return true; }
            else { return false; }
        }
        else if (cellRef.Equals(returnCellReference(tableRef)))
        {
            return true;
        } 
        else 
        {
            return false;
        }
    }
使用DocumentFormat.OpenXml.Spreadsheet;
使用DocumentFormat.OpenXml.Packaging;
专用静态数据表genericExcelTable(FileInfo文件名)
{
DataTable=新的DataTable();
尝试
{
使用(SpreadsheetDocument doc=SpreadsheetDocument.Open(fileName.FullName,false))
{
工作簿wkb=doc.WorkbookPart.Workbook;
工作表wks=wkb.subjects().FirstOrDefault();
SharedStringTable sst=wkb.WorkbookPart.SharedStringTablePart.SharedStringTable;
列出allSSI=sst.substands().ToList();
工作表部分wksp=(工作表部分)doc.WorkbookPart.GetPartById(wks.Id);
foreach(wksp中的表格定义部分tdp.表格定义部分)
{
QueryTablePart qtp=tdp.QueryTableParts.FirstOrDefault();
表excelTable=tdp.Table;
int colcounter=0;
foreach(excelTable.TableColumns中的TableColumn列)
{
DataColumn dcol=dataTable.Columns.Add(col.Name);
dcol.SetOrdinal(colcounter);
colcounter++;
}
SheetData data=wksp.Worksheet.Elements().First();
foreach(数据中的DocumentFormat.OpenXml.Spreadsheet.Row)
{
if(isInTable(row.subjects().FirstOrDefault(),excelTable.Reference,true))
{
int-cellcount=0;
DataRow DataRow=dataTable.NewRow();
foreach(row.Elements()中的单元格)
{
if(cell.DataType!=null&&cell.DataType.InnerText==“s”)
{
dataRow[cellcount]=allSSI[int.Parse(cell.CellValue.InnerText)].InnerText;
}
其他的
{
dataRow[cellcount]=cell.CellValue.Text;
}
cellcount++;
}
dataTable.Rows.Add(dataRow);
}
}
}
}
//对数据表执行任何操作
返回数据表;
}
捕获(例外情况除外)
{
//处理错误
返回数据表;
}
}
私有静态元组returnCellReference(字符串cellRef)
{
int startIndex=cellRef.IndexOfAny(“0123456789.ToCharArray());
string column=cellRef.Substring(0,startIndex);
int row=Int32.Parse(cellRef.Substring(startIndex));
返回新元组(TextToNumber(列),行);
}
私有静态int-TextToNumber(字符串文本)
{
返回文本
.选择(c=>c-'A'+1)
.合计((总和,下一个)=>总和*26+下一个);
}
私有静态bool不可见(Cell testCell、string tableRef、bool headerRow){
foreach (Row row in sheetData.Elements<Row>())
{
   foreach (Cell cell in row.Elements<Cell>())
   {
      string text = cell.CellValue.Text;
      // Do something with the cell value
   }
}
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;

    private static DataTable genericExcelTable(FileInfo fileName)
    {
        DataTable dataTable = new DataTable();
        try
        {
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fileName.FullName, false))
            {
                Workbook wkb = doc.WorkbookPart.Workbook;
                Sheet wks = wkb.Descendants<Sheet>().FirstOrDefault();
                SharedStringTable sst = wkb.WorkbookPart.SharedStringTablePart.SharedStringTable;
                List<SharedStringItem> allSSI = sst.Descendants<SharedStringItem>().ToList<SharedStringItem>();
                WorksheetPart wksp = (WorksheetPart)doc.WorkbookPart.GetPartById(wks.Id);

                foreach (TableDefinitionPart tdp in wksp.TableDefinitionParts)
                {
                    QueryTablePart qtp = tdp.QueryTableParts.FirstOrDefault<QueryTablePart>();
                    Table excelTable = tdp.Table;
                    int colcounter = 0;
                    foreach (TableColumn col in excelTable.TableColumns)
                    {
                        DataColumn dcol = dataTable.Columns.Add(col.Name);
                        dcol.SetOrdinal(colcounter);
                        colcounter++;
                    }

                    SheetData data = wksp.Worksheet.Elements<SheetData>().First();

                    foreach (DocumentFormat.OpenXml.Spreadsheet.Row row in data)
                    {
                        if (isInTable(row.Descendants<Cell>().FirstOrDefault(), excelTable.Reference, true))
                        {
                            int cellcount = 0;
                            DataRow dataRow = dataTable.NewRow();
                            foreach (Cell cell in row.Elements<Cell>())
                            {

                                if (cell.DataType != null && cell.DataType.InnerText == "s")
                                {
                                    dataRow[cellcount] = allSSI[int.Parse(cell.CellValue.InnerText)].InnerText;
                                }
                                else
                                {
                                    dataRow[cellcount] = cell.CellValue.Text;
                                }
                                cellcount++;
                            }
                            dataTable.Rows.Add(dataRow);
                        }
                    }
                }
            }
            //do whatever you want with the DataTable
            return dataTable;
        }
        catch (Exception ex)
        {
            //handle an error
            return dataTable;
        }
    }
    private static Tuple<int, int> returnCellReference(string cellRef)
    {
        int startIndex = cellRef.IndexOfAny("0123456789".ToCharArray());
        string column = cellRef.Substring(0, startIndex);
        int row = Int32.Parse(cellRef.Substring(startIndex));
        return new Tuple<int,int>(TextToNumber(column), row);
    }
    private static int TextToNumber(string text)
    {
        return text
            .Select(c => c - 'A' + 1)
            .Aggregate((sum, next) => sum * 26 + next);
    }
    private static bool isInTable(Cell testCell, string tableRef, bool headerRow){
        Tuple<int, int> cellRef = returnCellReference(testCell.CellReference.ToString());
        if (tableRef.Contains(":"))
        {
            int header = 0;
            if (headerRow)
            {
                header = 1;
            }
            string[] tableExtremes = tableRef.Split(':');
            Tuple<int, int> startCell = returnCellReference(tableExtremes[0]);
            Tuple<int, int> endCell = returnCellReference(tableExtremes[1]);
            if (cellRef.Item1 >= startCell.Item1
                && cellRef.Item1 <= endCell.Item1
                && cellRef.Item2 >= startCell.Item2 + header
                && cellRef.Item2 <= endCell.Item2) { return true; }
            else { return false; }
        }
        else if (cellRef.Equals(returnCellReference(tableRef)))
        {
            return true;
        } 
        else 
        {
            return false;
        }
    }