VSTO C#Excel工作簿所有工作表
我正在使用C#VSTO对目录中的所有Excel文件进行文本替换。目前,我的代码有效,但仅适用于每个Excel文件的活动工作表(第一个工作表)。如何对Excel文件中的所有现有工作表执行此操作:VSTO C#Excel工作簿所有工作表,c#,excel,vsto,C#,Excel,Vsto,我正在使用C#VSTO对目录中的所有Excel文件进行文本替换。目前,我的代码有效,但仅适用于每个Excel文件的活动工作表(第一个工作表)。如何对Excel文件中的所有现有工作表执行此操作: public void runFiles(string _path) { string path = _path; object m = Type.Missing; var xlApp = new Microsoft
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
,但出现了一个错误无法将类型“Microsoft.Office.Interop.Excel.Sheets”隐式转换为“Microsoft.Office.Interop.Excel.Worksheet”。存在显式转换(是否缺少转换?
工作表
属性是工作表的集合。所以你只需要迭代它
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);
}
工作表
方法返回工作表数组。我必须这样做来编辑数组中的每个元素
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();