如何通过oledb阅读器或excel库,excel datareader或NPOI等(Interop除外)如何检查一个单元格包含公式或不在Excel中?

如何通过oledb阅读器检查一个Cell是否包含公式或不在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); 

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

要做到这一点,你需要添加一个对OpenXML库的引用,这可以通过nuget包完成 (你还需要对WindowsBase的引用)。 然后,您需要加载电子表格,find您感兴趣的工作表并重复单元格。

每个Cell都有一个CellFormula属性,如果在该单元格中有一个公式,则该属性将是非空的。

作为一个例子,下面的代码将迭代每个单元格,并为任何具有公式的单元格输出一行。 如果任何单元格中有一个公式,它将返回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; } 

这可以通过文件的名称和感兴趣的工作表的名称来调用,尽pipe更新代码来迭代所有工作表是很简单的。 一个示例调用:

 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; } 

你可以探索一下: Range.HasFormulacom-interop

我也注意到有一个post可以即兴地满足您的需求。

这是一个框架 – 不是确切的语法。

 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 , 这篇文章可以帮助开始。 如果您仍然需要帮助,请随时发表评论。

我得到的解决scheme,但只有在互操作服务!

 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。 这个文件包含这样的条目:

 <cr="G3" i="1" l="1"/><cr="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();