问题描述
我正在尝试从C#中的Excel文档中解析文本.问题是我找不到检测(并忽略)空白单元格的方法.
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.
我在Visual Studio 2010 C#中使用Microsoft.Office.Interop.Excel.我不能跳过空白单元格,因此我的程序将因此存储空白值.
I'm using Microsoft.Office.Interop.Excel in Visual Studio 2010 C#. I can't skip blank cells so my program will consequentially store blank values.
我通过以下方式定义了我的woorksheet:
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];
我通过ws.Cells[row, col]
访问我的单元格.我尝试了不同的方法.仅举几例:
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 == ""
并且还显式地使用Range对象Excel.Range rng = ws.Cells[row, col]
要使用rng.Value2
And also using the Range object explicitelyExcel.Range rng = ws.Cells[row, col]
To use rng.Value2
根据我使用的方法,我会得到不同的错误,HRESULT的异常:0x800A03EC是其中之一.
Depending on which approach I use I get different errors, Exception from HRESULT: 0x800A03EC is one of them.
推荐答案
您可能应该使用SpecialCells.例如.下面的代码将所有空白单元格的值设置为零(vba代码).
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
这篇关于在C#中使用interop.excel检测空白Excel单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!