.NET读取Office文件内容(word、excel、ppt)

引用命名空间

 using Microsoft.Office.Core;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;

Word文件的读取

  public string ReadFile()
{
string text = string.Empty;
Word.ApplicationClass app = null;
Word.Document doc = null;
object readOnly = true;
object missing = System.Reflection.Missing.Value;
object fileName = this.FileInstance.FullName;
try
{
app = new Microsoft.Office.Interop.Word.ApplicationClass();
doc = app.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
text = doc.Content.Text.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty);
}
catch
{ }
finally
{
doc.Close(ref missing, ref missing, ref missing);
doc = null;
app.Quit(ref missing, ref missing, ref missing);
app = null;
}
return text;
}

Excel文件的读取

 public string ReadFile()
{
string text = string.Empty;
Excel.ApplicationClass app = null;
Excel.Workbook book = null;
object readOnly = true;
object missing = System.Reflection.Missing.Value;
object fileName = this.FileInstance.FullName;
try
{
app = new Microsoft.Office.Interop.Excel.ApplicationClass();
book = app.Workbooks.Open(fileName.ToString(), missing, readOnly, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
foreach (Excel.Worksheet sheet in book.Sheets)
{
for (int i = ; i <= sheet.UsedRange.Cells.Rows.Count; i++)
{
for (int j = ; j <= sheet.UsedRange.Cells.Columns.Count; j++)
{
text += ((Excel.Range)sheet.Cells[i, j]).Text.ToString().Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty) + " ";
}
}
}
}
catch
{ }
finally
{
book.Close(missing, fileName, missing);
book = null;
app.Quit();
app = null;
}
return text;
}

PPT文件的读取

  public override string ReadFile()
{
string text = string.Empty;
PowerPoint.ApplicationClass app = null;
PowerPoint.Presentation pp = null;
object readOnly = true;
object missing = System.Reflection.Missing.Value;
object fileName = this.FileInstance.FullName; try
{
app = new Microsoft.Office.Interop.PowerPoint.ApplicationClass();
pp = app.Presentations.Open(fileName.ToString(), Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse); foreach (PowerPoint.Slide slide in pp.Slides)
{
foreach (PowerPoint.Shape shape in slide.Shapes)
{
text += shape.TextFrame.TextRange.Text.Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty) + " ";
}
}
}
catch
{ }
finally
{
pp.Close();
pp = null;
app.Quit();
app = null;
} return text;
}
上一篇:Haskell语言学习笔记(57)Parsec(4)


下一篇:java ssh