我想找一些例如“Joe”的文本并将其从C#中的Excel工作表中删除它?
答案 0 :(得分:7)
您需要使用Range.Replace方法,只需替换为空字符串即可。
static void ReplaceTextInExcelFile(string filename, string replace, string replacement)
{
object m = Type.Missing;
// open excel.
Application app = new ApplicationClass();
// open the workbook.
Workbook wb = app.Workbooks.Open(
filename,
m, false, m, m, m, m, m, m, m, m, m, m, m, m);
// get the active worksheet. (Replace this if you need to.)
Worksheet ws = (Worksheet)wb.ActiveSheet;
// get the used range.
Range r = (Range)ws.UsedRange;
// call the replace method to replace instances.
bool success = (bool)r.Replace(
replace,
replacement,
XlLookAt.xlWhole,
XlSearchOrder.xlByRows,
true, m, m, m);
// save and close.
wb.Save();
app.Quit();
app = null;
}
答案 1 :(得分:0)
适用于Excel 2016
:
Microsoft.Office.Interop.Excel
,将其复制到C#项目中,并将其作为参考。15.0.0.0
。代码:
Excel.DisplayAlerts = false; // Prevent "Nothing found" dialogs.
var Excel = (Microsoft.Office.Interop.Excel.Application)ExcelDnaUtil.Application;
foreach(Worksheet sheet in Excel.Sheets)
{
bool success = sheet.Rows.Replace(What: "ABC",Replacement: "DEF");
}
Excel.DisplayAlerts = true;