c# - Excel.Interop 的 Worksheet.UsedRange 属性中可能存在错误?

标签 c# excel

看一下下面的代码。基本上,这是一个被调用的函数,用于识别工作表的使用范围、循环该范围并散列社会安全号码。

问题就在这里。如果我创建一个电子表格并填充一个单元格,该函数不会对该单元格进行哈希处理。但是,如果我填充多个,它就会起作用。

这可能是UsedRange 属性中的一个错误吗?或者我错过了什么?

非常感谢。

伍迪

try
{
    foreach (Excel.Worksheet ws in _excelWorksheet)
    {
        // Grab the range of numbers that populates the XLS.
        Excel.Range range = ws.UsedRange;
        // In the following cases, Value2 returns different types:
        //
        // 1. The range variable points to a single cell:
        // Value2 returns a object
        //
        // 2. The range variable points to many cells:
        // Value2 returns object[,]

        object[,] values = (object[,])range.Value2;

        for (int row = 1; row <= values.GetUpperBound(0); row++)
            for (int col = 1; col <= values.GetUpperBound(1); col++)
            {
                // Convert values to strings.
                string value = Convert.ToString(values[row, col]);

                // Mask the value that we retrieved and store it in a variable.
                switch (_mdOptions.cbobxEncryption.Text)
                {
                    case "MD5":
                    {
                        replaceSSN = SHA2Hash.ComputeHash(value, "MD5", null);
                        break;
                    }
                    case "SHA256":
                    {
                        replaceSSN = SHA2Hash.ComputeHash(value, "SHA256", null);
                        break;
                    }
                    default:
                    {
                        replaceSSN = SHA2Hash.ComputeHash(value, "SHA256", null);
                        break;
                    }
                }    

                // Match expressions to sensitive data and replace with the hash
                // value.
                if (Regex.IsMatch(value, @"\b[0-9]{3}-[0-9]{2}-[0-9]{4}\b"))
                {
                    range.Cells.set_Item(row, col, replaceSSN);
                }
                else if (Regex.IsMatch(value, @"\b[0-9]{3}[0-9]{2}[0-9]{4}\b"))
                {
                    range.Cells.set_Item(row, col, replaceSSN);
                }
            }
        }
    }
    catch (Exception)
    {
        // This is here because of a non-fatal error that we're getting with
        // Windows 7 during the hashing phase. Everything still works,
        // it's just that this error keeps popping up.

        // REVIEW FOR WINDOWS 7 COMPATABILITY
        ;

        //MessageBox.Show("There was a major error. Please restart the program.");
        //MessageBox.Show(@"Exception: " + ee);
    }


    // Pull the hashed password from the registry and add it to the SaveAs
    //string saveAsPassword = Convert.ToString(Registry.GetValue(@"HKEY_CURRENT_USER\Software\Mask Data", "Password", ""));
    /*
    _excelWorkbook.SaveAs("Results.xls",
    Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, false,
    Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
    Type.Missing, true, Type.Missing,
    Type.Missing, Type.Missing); 
     */
     // Report success.    
    MessageBox.Show("File masked successfully.", 
        "Mask Data", MessageBoxButtons.OK, MessageBoxIcon.Information,
        MessageBoxDefaultButton.Button1, 
        MessageBoxOptions.DefaultDesktopOnly);
    // Shutdown instance of Excel.
    //_excelApp.Quit();

    // Release memory.
    GC.Collect();
    GC.WaitForPendingFinalizers();
    Marshal.ReleaseComObject(_excelWorkbook);
    Marshal.ReleaseComObject(_excelApp);         
}

最佳答案

您无法将 double 转换为二维对象数组,因为 double 只有一维。如果我告诉你一些你已经知道的事情,但术语“ double ”意味着 double ,并且与二维数组(由 object[,] 定义)无关,我深表歉意。

您可以简单地为这种情况添加一个检查,因此前几行将如下所示:

XLS.Excel.Range range = ws.UsedRange;
object[,] values;
if (range.Value2.GetType().IsArray)
{
    values = (object[,])range.Value2;
}
else
{
    values = new object[2,2];
    values[1,1] = range.Value2;
}

我这台机器上没有 VS,因此代码未经测试,但应该非常接近

编辑: 敲出一个快速测试应用程序后,我可以看到UsedRange.Value2正在做什么 - 它返回所有工作表值的数组,这就是为什么如果有超过1个单元格它是一个数组,但是对于一个单元格它只会返回该值值(可以是任何类型)。上面的代码可以工作,但是有点破解。获取行数和列数的正确方法是使用:

range.Rows.Count

range.Columns.Count

如果您更改 for 循环以使用这两个值而不是数组边界,它将解决您的问题,并且适用于单行和多行

关于c# - Excel.Interop 的 Worksheet.UsedRange 属性中可能存在错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1295262/

相关文章:

c# - C# 中的 Azure 托管服务标识连接到 Azure SQL Server

c# - Visual Studio 中大型解决方案的最佳实践 (2008)

c# - 我的性能问题与WCF或网络有关吗?

c# - 检测在cloudflare后面连接的用户IP地址

excel - Microsoft Excel - 压缩行数

c# - 这个 LINQ 语句会返回 null 吗?

javascript - 在 SheetJS 中获取列名数组

vba - 应用程序.根据工作簿进行计算

javascript - 如何用 % 在 javascript 中计算

vba - 根据列中的条件复制一系列行并粘贴到名为条件的不同工作表中