C# 通过open xml sdk linq查询获取具有行和列位置的excel单元格值

C# 通过open xml sdk linq查询获取具有行和列位置的excel单元格值,c#,xml,linq,C#,Xml,Linq,任何人都知道如何使用open XML SDK 2.0获取excel单元格值,知道行和列的位置,例如(A2),通过Linq?所以excel直接或以字符串形式存储单元格值,存储在一个称为SharedString表的公共数据结构中 在下面的示例中,我们首先使用linq获取特定地址的单元,然后将其传递给另一个函数以获取单元的值 还要注意,您必须在每个阶段添加空检查,以确定行/列是否存在 using System.IO; using System.Linq; using System.Text.Regul

任何人都知道如何使用open XML SDK 2.0获取excel单元格值,知道行和列的位置,例如(A2),通过Linq?

所以excel直接或以字符串形式存储单元格值,存储在一个称为SharedString表的公共数据结构中

在下面的示例中,我们首先使用linq获取特定地址的单元,然后将其传递给另一个函数以获取单元的值

还要注意,您必须在每个阶段添加空检查,以确定行/列是否存在

using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace TestOpenXmlSDK
{
    class Program
    {
        static void Main(string[] args)
        {
            string pathSource = @"D:\sample.xlsx";
            using (FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fsSource.Length];
                fsSource.Read(bytes, 0, (int)fsSource.Length);
                using (MemoryStream mem = new MemoryStream())
                {
                    mem.Write(bytes, 0, (int)bytes.Length);
                    using (SpreadsheetDocument excelDocument = SpreadsheetDocument.Open(mem, true))
                    {
                        var wbPart = excelDocument.WorkbookPart;
                        var wsPart = wbPart.WorksheetParts.First();
                        var sheetData = wsPart.Worksheet.GetFirstChild<SheetData>();

                        var cellValue = GetCellValue(GetCell(sheetData, "B2"), wbPart);
                    }
                }
            }
        }

        public static Cell GetCell(SheetData sheetData, string cellAddress)
        {
            uint rowIndex = uint.Parse(Regex.Match(cellAddress, @"[0-9]+").Value);
            return sheetData.Descendants<Row>().FirstOrDefault(p => p.RowIndex == rowIndex).Descendants<Cell>().FirstOrDefault(p => p.CellReference == cellAddress);
        }

        public static string GetCellValue(Cell cell, WorkbookPart wbPart)
        {
            string value = cell.InnerText;
            if (cell.DataType != null)
            {
                switch (cell.DataType.Value)
                {
                    case CellValues.SharedString:
                        var stringTable = wbPart.GetPartsOfType<SharedStringTablePart>().FirstOrDefault();
                        if (stringTable != null)
                        {
                            value = stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
                        }
                        break;

                    case CellValues.Boolean:
                        switch (value)
                        {
                            case "0":
                                value = "FALSE";
                                break;
                            default:
                                value = "TRUE";
                                break;
                        }
                        break;
                }
            }
            return value;
        }
    }
}
使用System.IO;
使用System.Linq;
使用System.Text.RegularExpressions;
使用DocumentFormat.OpenXml.Packaging;
使用DocumentFormat.OpenXml.Spreadsheet;
命名空间TestOpenXmlSDK
{
班级计划
{
静态void Main(字符串[]参数)
{
字符串pathSource=@“D:\sample.xlsx”;
使用(FileStream fsSource=newfilestream(路径源,FileMode.Open,FileAccess.Read))
{
字节[]字节=新字节[fsSource.Length];
读取(字节,0,(int)fsSource.Length);
使用(MemoryStream mem=new MemoryStream())
{
mem.Write(字节,0,(int)字节.长度);
使用(电子表格文档excelDocument=SpreadsheetDocument.Open(mem,true))
{
var wbPart=excelDocument.WorkbookPart;
var wsPart=wbPart.WorksheetParts.First();
var sheetData=wsPart.Worksheet.GetFirstChild();
var cellValue=GetCellValue(GetCell(sheetData,“B2”),wbPart;
}
}
}
}
公共静态单元格GetCell(SheetData SheetData,字符串cellAddress)
{
uint rowIndex=uint.Parse(Regex.Match(cellAddress,@“[0-9]+”).Value);
返回sheetData.subjects().FirstOrDefault(p=>p.RowIndex==RowIndex).subjects().FirstOrDefault(p=>p.CellReference==cellAddress);
}
公共静态字符串GetCellValue(单元格、WorkbookPart wbPart)
{
字符串值=cell.InnerText;
if(cell.DataType!=null)
{
开关(cell.DataType.Value)
{
案例CellValues.SharedString:
var stringTable=wbPart.GetPartSoftType().FirstOrDefault();
if(stringTable!=null)
{
value=stringTable.SharedStringTable.ElementAt(int.Parse(value)).InnerText;
}
打破
大小写单元格值。布尔值:
开关(值)
{
案例“0”:
value=“FALSE”;
打破
违约:
value=“TRUE”;
打破
}
打破
}
}
返回值;
}
}
}
只需将此函数复制粘贴到程序中,然后调用 函数由下面的示例实现

(无需打开Excel或 s.Name==sheetName.FirstOrDefault()中的任何内容; //如果没有工作表,则引发异常。 如果(表==null) { 抛出新ArgumentException(“sheetName”); } //检索对工作表零件的引用。 工作表部件wsPart= (工作表部分)(wbPart.GetPartById(表Id)); //使用其工作表属性获取对单元格的引用 //其地址与您提供的地址匹配。 单元格theCell=wsPart.Worksheet.subjects()。 其中(c=>c.CellReference==addressName).FirstOrDefault(); //如果单元格不存在,则返回空字符串。 如果(cell.InnerText.Length>0) { 值=cell.InnerText; //如果单元格表示整数,则完成。 //对于日期,此代码返回 //表示日期。代码处理字符串和 //单独布尔。对于共享字符串,代码 //在共享字符串中查找相应的值 //对于布尔型,代码将值转换为 //这些词是真是假。 if(theCell.DataType!=null) { 开关(cell.DataType.Value) { 案例CellValues.SharedString: //对于共享字符串,请在 //共享字符串表。 var stringTable= wbPart.getPartSoftType() .FirstOrDefault(); //如果缺少共享字符串表,则 //错误。返回中的索引 //单元格。否则,请在中查找正确的文本 //桌子。 if(stringTable!=null) { 值= stringTable.SharedStringTable .ElementAt(int.Parse(value)).InnerText; } 打破 大小写单元格值。布尔值: 开关(值) { 案例“0”: value=“FALSE”; 打破 违约: value=“TRUE”; 打破
// Example GetCellValue(@"c:\test.xlsx", "Sheet1", "A1");
// Retrieve the value of a cell, given a file name, sheet name, 
// and address name.
public static string GetCellValue(string fileName, 
    string sheetName, 
    string addressName)
{
    string value = null;

    // Open the spreadsheet document for read-only access.
    using (SpreadsheetDocument document = 
        SpreadsheetDocument.Open(fileName, false))
    {
        // Retrieve a reference to the workbook part.
        WorkbookPart wbPart = document.WorkbookPart;

        // Find the sheet with the supplied name, and then use that 
        // Sheet object to retrieve a reference to the first worksheet.
        Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().
          Where(s => s.Name == sheetName).FirstOrDefault();

        // Throw an exception if there is no sheet.
        if (theSheet == null)
        {
            throw new ArgumentException("sheetName");
        }

        // Retrieve a reference to the worksheet part.
        WorksheetPart wsPart = 
            (WorksheetPart)(wbPart.GetPartById(theSheet.Id));

        // Use its Worksheet property to get a reference to the cell 
        // whose address matches the address you supplied.
        Cell theCell = wsPart.Worksheet.Descendants<Cell>().
          Where(c => c.CellReference == addressName).FirstOrDefault();

        // If the cell does not exist, return an empty string.
        if (theCell.InnerText.Length > 0)
        {
            value = theCell.InnerText;

            // If the cell represents an integer number, you are done. 
            // For dates, this code returns the serialized value that 
            // represents the date. The code handles strings and 
            // Booleans individually. For shared strings, the code 
            // looks up the corresponding value in the shared string 
            // table. For Booleans, the code converts the value into 
            // the words TRUE or FALSE.
            if (theCell.DataType != null)
            {
                switch (theCell.DataType.Value)
                {
                    case CellValues.SharedString:

                        // For shared strings, look up the value in the
                        // shared strings table.
                        var stringTable = 
                            wbPart.GetPartsOfType<SharedStringTablePart>()
                            .FirstOrDefault();

                        // If the shared string table is missing, something 
                        // is wrong. Return the index that is in
                        // the cell. Otherwise, look up the correct text in 
                        // the table.
                        if (stringTable != null)
                        {
                            value = 
                                stringTable.SharedStringTable
                                .ElementAt(int.Parse(value)).InnerText;
                        }
                        break;

                    case CellValues.Boolean:
                        switch (value)
                        {
                            case "0":
                                value = "FALSE";
                                break;
                            default:
                                value = "TRUE";
                                break;
                        }
                        break;
                }
            }
        }
    }
    return value;
}