Detect blank Excel cell using interop.excel in C#

别等时光非礼了梦想. 提交于 2020-03-23 06:25:07

问题


I'm trying to parse text from an Excel doc in C#. The problem is that I can't find a way to detect (and ignore) blank cells.

I've searched this forum and many others but I can still not get it to work.

I'm using Microsoft.Office.Interop.Excel in Visual Studio 2010 C#. I have no problem with opening Excel and reading and storing data in it. Its just that I can't skip blank cells so my program will consequentially store blank values.

I have defined my woorksheet the following way:

Excel.Application exApp = OpenExcel(); String mySheet = @"C:\sheet.xlsx"; Excel.Workbook wb = exApp.Workbooks.Open(mySheet); Excel.Worksheet ws = wb.Sheets[1];

I access my cells by ws.Cells[row, col]. And I've tried different approaches. To name a few:

ws.Cells[row, col].Value2 == null
ws.Cells[row, col].Value == null
ws.Cells[row, col].Value == ""

And also using the Range object explicitely Excel.Range rng = ws.Cells[row, col] To use rng.Value2

Depending on which apprach I use I get different errors, Exception from HRESULT: 0x800A03EC is one of them.

Have I missed something fundamental, surely this must be a common task?

If some kind soul could show me a good way to detect blank cells I would appreciate it very much!

Kind regards


回答1:


You should probably use SpecialCells. E.g. the code below sets the value of all empty cells to zero (vba code).

Range("e11:g16").SpecialCells(xlCellTypeBlanks).Value = 0

Or you can easily loop all empty cells like this:

For Each item In Range("e11:g16").SpecialCells(xlCellTypeBlanks)
   '...
Next

In the same logic, if you want to loop through all cells which are not empty:

 For Each item In Range("g10:h11").SpecialCells(xlCellTypeConstants)
        '...
 Next



回答2:


Try with the Text property of the Range object...

rng.Text == String.Empty



回答3:


Try this:

if (ws.IsEmpty(Cells[row, col]))

I don't exactly remember if I got the syntax right for porting to Excel from .NET, but this is the command I use in a VB macro from within Excel.

you can also try IsNumeric(Cells[row,col].Value)

The default value for Excel cells is Empty (but I can't find the MSN link to verify this!)

See: What is the difference between =Empty and IsEmpty() in VBA (Excel)?



来源:https://stackoverflow.com/questions/28435328/detect-blank-excel-cell-using-interop-excel-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!