//word 中表数据格式定义
public class DocTables
{
public string FileName { get; set; }
public string TableName { get; set; }
public System.Data.DataTable TableContent { get; set; }
}
/根据word文件名找到内部所有的表并返回,patternText 为标示目录表特有标记,如 '目录主表数据定义' 或 '主表数据定义'等
public static List<DocTables> GetTablesFromWordDoc(string filePath, string patternText = "主表数据定义"){
List<DocTables> lstTableWithNames = new List<DocTables>();
object oFileName = filePath;// @"D:\svn_repos\geps6.2\Docs\15.安全管理\07.安全管理活动\安全活动记录34.docx";
object oReadOnly = true;
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word._Application oWord = null;
Microsoft.Office.Interop.Word._Document oDoc = null;
Object nothing = System.Reflection.Missing.Value;
oWord = new Microsoft.Office.Interop.Word.Application();
try
{
oWord.Visible = false;
oDoc = oWord.Documents.Open(ref oFileName, ref oMissing, ref oReadOnly, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing);
for (int tablePos = 1; tablePos <= oDoc.Tables.Count; tablePos++)
{
DocTables docTable = new DocTables();
Microsoft.Office.Interop.Word.Table nowTable = oDoc.Tables[tablePos];
//3 代表sentence,4 代表paragraph,5 代表line
var tableName = nowTable.Range.Previous(4, 1).Text;
//不满足匹配字符,跳过该表
if (!tableName.Contains(patternText)) continue;
docTable.FileName = filePath;
docTable.TableName = tableName.Trim(new char[] { '\n', '\r' });
//string tableMessage = string.Format("第{0}/{1}个表:\n", tablePos, oDoc.Tables.Count);
System.Data.DataTable dt = new System.Data.DataTable();
for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
{
DataRow drNew = dt.NewRow();
int columnIndex = 0;
foreach (Cell cellObj in nowTable.Rows[rowPos].Cells)
{
columnIndex++;
drNew[columnIndex] = cellObj.Range.Text.Remove(cellObj.Range.Text.Length - 2, 2);//remove \r\a
}
dt.Rows.Add(drNew);
}
lstTableWithNames.Add(docTable);
}
object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
oWord.Quit(ref saveOption, ref nothing, ref nothing);
return lstTableWithNames;
}
catch
{
//
}
finally
{
if (oWord != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(oWord);
}
return null;
}