繁体   English   中英

如何在Excel中通过oledb reader或excel库,excel datareader或NPOI等检查Cell是否包含公式(Interop除外)?

[英]How to check a Cell contains formula or not in Excel through oledb reader or excel library, excel datareader or NPOI etc (Except Interop)?

如何通过oledb阅读器在Excel中检查单元格是否包含公式?

在此输入图像描述

System.Data.OleDb.OleDbConnection conn2 = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source = " + strFileName + "; Extended Properties = \"Excel 8.0;HDR=NO;IMEX=1\";");
conn2.Open();
string strQuery2 = "SELECT * FROM [" + Table + "]";

System.Data.OleDb.OleDbDataAdapter adapter2 = new System.Data.OleDb.OleDbDataAdapter(strQuery2, conn2);

System.Data.DataTable DT2 = new System.Data.DataTable();

adapter2.Fill(DT2);

您可以探索这个: Range.HasFormulacom-interop

我还注意到有一个帖子可以即兴创作来满足你的需求。

这是一个骨架 - 而不是确切的语法。

Excel.Application excelApp = new Excel.Application();
Excel.Workbook workBook = excelApp.Workbooks.Open(filePath);
Excel.WorkSheet WS = workBooks.WorkSheets("Sheet1");

Range rangeData = WS.Range["A1:C3"];    

foreach (Excel.Range c in rangeData.Cells)
{
    if (c.HasFormula)
    {
       MessageBox.Show(Convert.ToString(c.Value));
    }        
}

不确定如何使用OLEDB实现这一目标,因为您的查询似乎只是将单元格数据(文本,数字,没有公式) 抓取到查询中。

如果您必须使用OLEDB这篇文章可能有助于启动。 如果您仍需要帮助,请随时发表评论。

我得到了解决方案但只在Interop Services中!

public bool IsFormulaExistInExcel(string excelpath)
     {
        bool IsFormulaExist = false;
        try
        {
            Microsoft.Office.Interop.Excel.Application excelApp = null;
            Microsoft.Office.Interop.Excel.Workbooks workBooks = null;
            Microsoft.Office.Interop.Excel.Workbook workBook = null;
            Microsoft.Office.Interop.Excel.Worksheet workSheet;
            excelApp = new Microsoft.Office.Interop.Excel.Application();
            workBooks = excelApp.Workbooks;
            workBook = workBooks.Open(excelpath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
            workSheet = workBook.Worksheets.get_Item(1);
            Microsoft.Office.Interop.Excel.Range rng = workSheet.UsedRange;


            dynamic FormulaExist = rng.HasFormula;
            Type unknown = FormulaExist.GetType();

            if (unknown.Name == "DBNull")
                IsFormulaExist = true;
            else if (unknown.Name == "Boolean")
            {
                if (FormulaExist == false)
                    IsFormulaExist = false;
                else if (FormulaExist == true)
                    IsFormulaExist = true;
            }
        }
        catch (Exception E)
        {
        }
    return IsFormulaExist;
  }

我使用了Apache Poi Library ...它具有以下相关方法

if(cell.getCellType()==CellType.CELL_TYPE_FORMULA)
{
// this cell contains formula......
}

如果您的excel文件是.xlsx,因为.xlsx实际上是一个zip存档,您可以在其中读取xl \\ calcChain.xml。 此文件包含以下条目:

<c r="G3" i="1" l="1"/><c r="A3" i="1" l="1"/>

在该示例中,在单元格G3和A3中存在公式。 所以你可以这样做:

    // Add references for
    // System.IO.Compression
    // System.IO.Compression.FileSystem

    private static List<string> GetCellsWithFormulaInSheet(string xlsxFileName, int sheetNumber)
    {
        using (var zip = System.IO.Compression.ZipFile.OpenRead(xlsxFileName))
        {
            var list = new List<string>();

            var entry = zip.Entries.FirstOrDefault(e => e.FullName == "xl/calcChain.xml");
            if (entry == null)
                return list;

            var xdoc = XDocument.Load(entry.Open());
            XNamespace ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

            return xdoc.Root.Elements(ns + "c")
                .Select(x => new { Cell = x.Attribute("r").Value, Sheet = int.Parse(x.Attribute("i").Value) })
                .Where(x => x.Sheet == sheetNumber)
                .Select(x => x.Cell)
                .ToList();
        }
    }

然后使用这样的方法:

var cellsWithFormula = GetCellsWithFormulaInSheet(@"c:\Book.xlsx", 1);
bool hasFormulaInSheet = cellsWithFormula.Any();

您可以使用OpenXML SDK读取Xlsx文件。

为此,您需要添加对OpenXML库的引用,这可以通过nuget包完成 (您还需要对WindowsBase的引用)。 然后,您需要加载电子表格,找到您感兴趣的工作表并迭代单元格。

每个Cell都有一个CellFormula属性,如果该单元格中有公式,则该属性将为非null。

例如,以下代码将迭代每个单元格并为具有公式的任何单元格输出一行。 如果任何单元格中有公式,它将返回true ; 否则会返回false

public static bool OutputFormulae(string filename, string sheetName)
{
    bool hasFormula = false;

    //open the document
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
    {
        //get the workbookpart
        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
        //get the correct sheet
        Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).First();
        if (sheet != null)
        {
            //get the corresponding worksheetpart
            WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;

            //iterate the child Cells
            foreach (Cell cell in worksheetPart.Worksheet.Descendants<Cell>())
            {
                //check for a formula
                if (cell.CellFormula != null && !string.IsNullOrEmpty(cell.CellFormula.Text))
                {
                    hasFormula = true;
                    Console.WriteLine("Cell {0} has the formula {1}", cell.CellReference, cell.CellFormula.Text);
                }
            }
        }
    }

    return hasFormula;
}

这可以使用文件名称和您感兴趣的工作表名称来调用,尽管更新代码以迭代所有工作表是微不足道的。 一个示例电话:

bool formulaExistsInSheet = OutputFormulae(@"d:\test.xlsx", "Sheet1");
Console.WriteLine("Formula exists? {0}", formulaExistsInSheet);

上面的示例输出:

电池C1具有式A1 + B1
细胞B3具有式C1 * 20
公式存在? 真正

如果您只对片材中有任何具有公式的单元格感兴趣,可以使用Any扩展方法简化上述操作:

public static bool HasFormula(string filename, string sheetName)
{
    bool hasFormula = false;
    //open the document
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(filename, false))
    {
        //get the workbookpart
        WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;
        //get the correct sheet
        Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).First();
        if (sheet != null)
        {
            //get the corresponding worksheetpart
            WorksheetPart worksheetPart = workbookPart.GetPartById(sheet.Id) as WorksheetPart;

            hasFormula = worksheetPart.Worksheet.Descendants<Cell>().Any(c =>
                c.CellFormula != null && !string.IsNullOrEmpty(c.CellFormula.Text));
        }
    }

    return hasFormula;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM