获取WOED和EXCEL的公用方法

时间:2024-01-11 13:27:56
       1. 需要传入word地址

        /// <summary>
/// 获取WORD内容
/// </summary>
/// <param name="docFileName"></param>
/// <returns></returns>
public string Doc2Text(string docFileName)
{
Word.Application app = new Microsoft.Office.Interop.Word.Application();
object fileobj = docFileName;
object nullobj = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Document doc =
app.Documents.Open(ref fileobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj,
ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj
);
string outText = doc.Content.Text;
doc.Close(ref nullobj, ref nullobj, ref nullobj);
app.Quit(ref nullobj, ref nullobj, ref nullobj);
return outText;
}

2. 传入Excel的路径即可

         /// <summary>
/// 读取Excel
/// </summary>
/// <param name="strFileName"></param>
public string ResumeExcel(string path)
{
string str = string.Empty;
//创建Application对象
Excel.Application xApp = new Excel.ApplicationClass();
xApp.Visible = false; object Missing = System.Reflection.Missing.Value;
//得到WorkBook对象,
Excel.Workbook xBook = xApp.Workbooks.Open(path, Missing, Missing, Missing, Missing,
Missing, Missing, Missing, Missing,
Missing, Missing, Missing, Missing); //指定要操作的Sheet:
Excel.Worksheet xSheet = (Excel.Worksheet)xBook.Sheets[]; //读取,通过Range对象,但使用不同的接口得到Range
for (int i = ; i <= ; i++)
{
for (int j = ; j <= ; j++)
{
Excel.Range rng = (Excel.Range)xSheet.Cells[i, j];
if (rng.Value2 != null)
{
str += rng.Value2.ToString();
}
}
}
xApp.Quit();
return str;
}
    3. 打开word或者Excel后要杀死进程,以免下次打开报错
public void KillProcess()
{
System.Diagnostics.Process[] myPs;
myPs = System.Diagnostics.Process.GetProcesses();
string myS = "EXCEL.EXE";
foreach (System.Diagnostics.Process p in myPs)
{
try
{
if (p.Modules != null)
if (p.Modules.Count > )
{
System.Diagnostics.ProcessModule pm = p.Modules[];
if (pm.ModuleName.ToLower() == "excel.exe")
p.Kill();
}
}
catch
{ }
finally
{
}
}
}