0

我正在尝试访问文件夹中存在的多个 excel 文件,然后找到一个特定的工作表,然后搜索一个特定的列(标题位于工作表的第一行)。该列包含数值,我需要对工作表的该列的所有值求和,然后将总和粘贴到创建新 excel 的表中。输出 excel 应包含具有该列的所有值总和的表我访问的 excel

计划努力 || 实际努力|| 部署者||

粗体字母字段是 Excel 工作表的标题,我需要找到文件夹中所有 Excel 的“实际工作量”列的数值总和。

以下是我的代码。在搜索列后,我一直无法读取列值。我正在使用 C# 语言和 Microsoft.Interop dll ver 12.0 并且系统中存在 MS excel 2007

类程序{

    static void Main(string[] args)
    {
        Excel.Application application = new Excel.Application();

        Excel.Workbook xlWorkBook;
        Excel.Sheets sheets;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;
        System.Array myValues;
        string findName = "Actual Effort";

        string[] path = Directory.GetFiles(@"C:\Users\Documnents\Projects\ReadExcelApp\*.xls");

       foreach (string xlPath in path)
        {
            xlWorkBook = application.Workbooks.Open(xlPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
            Type.Missing, Type.Missing, Type.Missing, Type.Missing);

            sheets = xlWorkBook.Worksheets;
            xlWorkSheet = (Excel.Worksheet)sheets.get_Item(3);
            range = xlWorkSheet.UsedRange;

            string findColumnValue = RetrieveColumnValue(xlWorkSheet, findName);
           //string colCount = findColumnValue.(Stuck at this line:how to access the column values)

        }
    }
    public static string RetrieveColumnValue(Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet, string findName)
    {
        Excel.Range rng = xlWorkSheet.UsedRange;
        Excel.Range rngResult = null;
        rngResult = rng.Find(findName, Type.Missing, Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlPart, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext,
            Type.Missing, Type.Missing, Type.Missing);
        if (rngResult != null)
        {
            Excel.Range cRng = null;
            int rowused = rng.Rows.Count;

            string returnStr;
            for (int i = 1; i < rowused; i++)
            {
                cRng = (Excel.Range)xlWorkSheet.Cells[i, rngResult.Column];
                if (cRng != null)
                {
                    returnStr = cRng.Name.ToString();
                }

            }
            return returnStr;
        }
        else
        {
            return string.Empty;
        }
    }

}

另外,是否有可能一旦它运行,我可以在具有 MS Office 2010 的系统中执行 exe 吗?

4

1 回答 1

0

试试这个来总结列值:

        decimal returnVal = 0;
        for (int i = 1; i < rowused; i++) //NB: off-by-one error here? Shouldn't it be from 1 to <= rows ?
        {
            cRng = (Excel.Range)xlWorkSheet.Cells[i, rngResult.Column];
            if (cRng != null)
            {
                decimal currentVal;
                if( decimal.TryParse(cRng.Value2.ToString(), out currentVal) )
                    returnVal += currentVal;
            }
        }
        return returnVal.ToString();
于 2013-09-26T13:15:31.717 回答