定义标记数据:
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();//获取应用
Microsoft.Office.Interop.Word._Document oDoc = oWord.Documents.Add(ref oTemplate, ref oMissing, ref oMissing, ref oMissing);//
书签的定义
object[] oBookMark = new object[9];
oBookMark[0] = "TestData"; //oBookMark[30]
oBookMark[1] = "Result";//oBookMark[31]
oBookMark[2] = "Result2";//oBookMark[32]
oBookMark[3] = "remark2"; //oBookMark[33]
oBookMark[4] = "Table1"; //oBookMark[30]
oBookMark[5] = "Table2";//oBookMark[31]
oBookMark[6] = "Table3";//oBookMark[32]
oBookMark[7] = "ReportTime"; //oBookMark[30]
oBookMark[8] = "TestNo";//oBookMark[31]
表格操作(插入表到ref oBookMark[6]) 书签这里)
Microsoft.Office.Interop.Word.Table Table3 = oDoc.Tables.Add(oDoc.Bookmarks.get_Item(ref oBookMark[6]).Range, (int)Math.Ceiling((decimal)ListTable3.Count / 2), 4);
Table3.set_Style("网格型");
///第三张表
for (int i = 0; i < (int)Math.Ceiling((decimal)ListTable3.Count / 2); i++)
{
Table3.Cell(i+1, 1).Range.Text = ListTable3[2 * i].CanshuName;
Table3.Cell(i+1, 2).Range.Text = ListTable3[2 * i].CanshuValue;
if (ListTable3.Count>2 * i + 1)
{
Table3.Cell(i + 1, 3).Range.Text = ListTable3[2 * i + 1].CanshuName;
Table3.Cell(i + 1, 4).Range.Text = ListTable3[2 * i + 1].CanshuValue;
}
}
插入光标 删除对应的数据(光标是以为doc首行为起始点)
object unite = WdUnits.wdStory;
var selection = oDoc.Application.Selection;
selection.MoveDown(Nothing, 20);//将光标转移到第二十个下面
//object unite = WdUnits.wdWord;
/// 删除空白行
for (int i = 0; i < (31 - CreateTableCount); i++)
{
selection.MoveDown(Nothing, 1);
selection.Delete();//删除当前光标处
//oDoc.Application.Selection.MoveDown("\n"); //将光标移动到文档末尾
//oDoc.Content.InsertAfter("\n");
//Microsoft.Office.Interop.Word.Paragraph p1 = oDoc.Content.Paragraphs.Add(ref oMissing);
}
word转换为pdf
public bool WordToPDF(string sourcePath, string targetPath)
{
bool result = false;
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document
document = null;
try
{
application.Visible = false;
document = application.Documents.Open(sourcePath);
document.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
result = true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
result = false;
}
finally
{
document.Close();
}
return result;
}
word数据保存
oDoc.SaveAs(ref filename, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
oDoc.Close(ref oMissing, ref oMissing, ref oMissing);
//关闭word
oWord.Quit(ref oMissing, ref oMissing, ref oMissing);