Excel范围在C#使用interop.Excel。范围既空又不空? [英] Excel Range in C# using interop.Excel. Range both empty and not empty?

查看:191
本文介绍了Excel范围在C#使用interop.Excel。范围既空又不空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Excel工作表,看起来像这样。
| A1 | B1 | 空白| D1 | E1 | F1 |
即仅第一行填充第三列是空白的。我在C#中以下列方式使用interop.excel解析此:

I have a Excel sheet that looks like this. |A1|B1| "BLANK" |D1|E1|F1| I.e. only the first row is populated and the third column is blank. I parse this in C# using interop.excel in the following way:

        Excel.Application exApp = OpenExcel();
        String mySheet = @"C:\c#\rapport.xlsx";
        Excel.Workbook wb = exApp.Workbooks.Open(mySheet);
        Excel.Worksheet ws = wb.Sheets[1];
        Excel.Range row = ws.Rows[1];



我创建了一个新的范围仅由

I create a new range only containing the non-empty cells in row 1 by

        Excel.Range rng = row.SpecialCells(Excel.XlCellType.xlCellTypeConstants);

现在:如果我使用 rng.Select 在我的表中的所有非空单元格被选中。如果我用 rng.Count 将返回5,这是一个非空单元格在我的片数。不过还是当我利用细胞打印单元:

Now: if I use rng.Select all the non-empty cells in my sheet is selected. And if I use rng.Count it will return 5, which is the number of non-empty cells in my sheet. But still when I print cell by cell using:

Console.WriteLine(rng[1,i].Value.ToString());



这表明,RNG [1,1-2]包含A1和B1,这是很好。但是,
RNG [1,3]为空或空。和RNG [1,4-7]包含D1-F1。

It shows that rng[1, 1-2] contains "A1 and B1", this is nice. But rng[1, 3] is empty or null. And rng[1, 4-7] contains D1-F1.

这怎么可能?

我的主要目标是将所有非空值存储在一个字符串数组。但是因为我的范围RNG既是空,非空的是一些奇怪的方式,我无法选择正确的价值观。

My main goal is to store all non-empty values in a string array. But I can't select the right values because my range rng is both empty and non-empty is some weird way.

推荐答案

这解决了它!不过,我没有使用.Item方法来存储值作为罗里提出建议。日Thnx罗里!

This solved it! However I didn't use the .Item method to store the values as Rory suggested suggested. Thnx Rory!

        string[] str = new String[rng.Count];
        int i = 0;

        foreach (Excel.Range cell in rng.Cells)
        {
            str[i] = cell.Value.ToString();
            i++;
        }

        for (int j = 0; j < str.Length; j++)
            Console.WriteLine(str[j]);

这篇关于Excel范围在C#使用interop.Excel。范围既空又不空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆