简体   繁体   English

使用interop.Excel在C#中使用Excel Range。 范围既为空又为非空?

[英]Excel Range in C# using interop.Excel. Range both empty and not empty?

I have a Excel sheet that looks like this. 我有一个看起来像这样的Excel工作表。 |A1|B1| | A1 | B1 | "BLANK" |D1|E1|F1| “空白” | D1 | E1 | F1 | Ie only the first row is populated and the third column is blank. 即仅填充第一行,第三列为空白。 I parse this in C# using interop.excel in the following way: 我通过以下方式使用interop.excel在C#中对此进行解析:

        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 我创建了一个新范围,仅包含第1行中的非空单元格

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

Now: if I use rng.Select all the non-empty cells in my sheet is selected. 现在:如果我使用rng.Select ,则选择工作表中的所有非空单元格。 And if I use rng.Count it will return 5, which is the number of non-empty cells in my sheet. 如果我使用rng.Count ,它将返回5,这是工作表中非空单元格的数量。 But still when I print cell by cell using: 但是仍然当我使用以下命令逐个打印单元时:

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

It shows that rng[1, 1-2] contains "A1 and B1", this is nice. 它显示rng [1,1-2]包含“ A1和B1”,这很好。 But rng[1, 3] is empty or null. 但是rng [1,3]为空或为null。 And rng[1, 4-7] contains D1-F1. 并且rng [1,4-7]包含D1-F1。

How is this possible? 这怎么可能?

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. 但是我无法选择正确的值,因为我的范围rng既是空的又是非空的,这是有些奇怪的方法。

Try using: 尝试使用:

ws.Columns.ClearFormats();
ws.Rows.ClearFormats();

to be sure your Range excludes formatted but empty cells. 确保您的范围排除格式化的但为空的单元格。

Another try could be to get : 另一种尝试可能是:

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

This solved it! 这样解决了! However I didn't use the .Item method to store the values as Rory suggested suggested. 但是,我没有使用.Item方法来存储Rory建议的值。 Thnx Rory! 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]);

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

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