62,046
社区成员
发帖
与我相关
我的任务
分享
private string ReplaceExcel(string filePath, string strOld, string strNew)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
excel.Visible = false;
//excel.
string modelFile = filePath; //文件名
Workbook wb = excel.Workbooks._Open(modelFile, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value
, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Worksheet xSheet = (Worksheet)wb.Sheets[1];
int icount = wb.Sheets.Count;
for (int i = 1; i <= icount; i++)
{
try
{
xSheet = (Worksheet)wb.Sheets[i];
object what = strOld; //查找字符串
object retxt = strNew; //替换字符串
xSheet.Cells.Replace(what, retxt, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//excel.Visible = false;
}
catch
{
}
}
object myNothing = Missing.Value;
object myFileName = HttpContext.Current.Server.MapPath(FLYSO.ToolKit.Fun.GetNo + ".xls");
try
{
wb.SaveAs(myFileName, myNothing, myNothing, myNothing, myNothing, myNothing,
XlSaveAsAccessMode.xlExclusive, myNothing, myNothing, myNothing, myNothing, myNothing);
NAR(xSheet);
wb.Close(false, Missing.Value, Missing.Value);
NAR(wb);
excel.Quit();
NAR(excel);
System.GC.Collect();
}
catch
{
FLYSO.ToolKit.alert.Message("操作Excel文档失败!");
}
//wb.Save();
//NAR(xSheet);
//wb.Close(false, Missing.Value, Missing.Value);
//NAR(wb);
//excel.Quit();
//NAR(excel);
//System.GC.Collect();
return myFileName.ToString();
}
private void NAR(object o)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);//强制释放一个对象
}
catch
{
}
finally
{
o = null;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string abc = ReplaceExcel(MapPath("ccc.xls"), "项目施工管理情况一览表", "项目施工管理情况一览表YTZ123");
Response.Write(abc + "成功!");
}