VSTO C#Excel工作簿所有工作表

时间:2019-12-13 17:00:03

标签: c# excel vsto

我正在使用C#VSTO在目录中的所有Excel文件中进行文本替换。目前,我的代码有效,但仅适用于每个Excel文件的活动工作表(第一个工作表)。如何对Excel文件中的所有现有工作表执行此操作:

public void runFiles(string _path)
        {
            string path = _path;
            object m = Type.Missing;

            var xlApp = new Microsoft.Office.Interop.Excel.Application();

            DirectoryInfo d = new DirectoryInfo(path);

            FileInfo[] listOfFiles_1 = d.GetFiles("*.xlsx*").ToArray();
            FileInfo[] listOfFiles_2 = d.GetFiles("*.xls*").ToArray();

            FileInfo[] listOfFiles = listOfFiles_1.Concat(listOfFiles_2).ToArray();

            xlApp.DisplayAlerts = false;
            foreach (FileInfo file in listOfFiles)
            {

                var xlWorkBook = xlApp.Workbooks.Open(file.FullName);
                Excel.Worksheet xlWorkSheet = xlWorkBook.Worksheets;

                // get the used range. 
                Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;

                // call the replace method to replace instances. 
                bool success = (bool)r.Replace(
                    "Engineer",
                    "Designer",
                    Excel.XlLookAt.xlWhole,
                    Excel.XlSearchOrder.xlByRows,
                    true, m, m, m);

                xlWorkBook.Save();
                xlWorkBook.Close();
            }

            xlApp.Quit();

            Marshal.ReleaseComObject(xlApp);
        }

xlWorkBook.ActiveSheet仅抓取第一张纸。我尝试了xlWorkBook.Worksheets,但遇到了Cannot implicitly convert type 'Microsoft.Office.Interop.Excel.Sheets' to 'Microsoft.Office.Interop.Excel.Worksheet'. An explicit conversion exists (are you missing a cast?)

错误

2 个答案:

答案 0 :(得分:0)

Worksheets属性是工作表的集合。因此,您只需要遍历它。

foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
{
    // get the used range. 
    Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;

    // call the replace method to replace instances. 
    bool success = (bool)r.Replace(
        "Engineer",
        "Designer",
        Excel.XlLookAt.xlWhole,
        Excel.XlSearchOrder.xlByRows,
        true, m, m, m);
}

答案 1 :(得分:0)

Worksheets方法返回一个工作表数组。我必须通过这样做来编辑数组中的每个元素

                foreach (Excel.Worksheet xlWorkSheet in xlWorkBook.Worksheets)
                {
                    // get the used range. 
                    Excel.Range r = (Excel.Range)xlWorkSheet.UsedRange;

                    // call the replace method to replace instances. 
                    bool success = (bool)r.Replace(
                        "Engineer",
                        "Designer",
                        Excel.XlLookAt.xlWhole,
                        Excel.XlSearchOrder.xlByRows,
                        true, m, m, m);
                }
                xlWorkBook.Save();
                xlWorkBook.Close();