原地址是这个 https://blog.csdn.net/u011131296/article/details/9167005,然后进行了修改。
1.引用dll
2.操作模板,先复制一份临时文件,然后对临时文件进行操作,最后另存为选择指定位置。
namespace WindowsFormsApp1 {
public partial class Print : Form {
/*=================================================*/
Microsoft.Office.Interop.Word.Document doc;
Microsoft.Office.Interop.Word.Application app;
private static string TemplateFile1 = System.Windows.Forms.Application.StartupPath + "\\全水分测定原始记录.doc";
private static string temppath = System.Windows.Forms.Application.StartupPath + "\\全水分测定原始记录_temp.doc"; //临时文件
/*=================================================*/
public Print() {
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e) {
foreach (System.Diagnostics.Process p in System.Diagnostics.Process.GetProcessesByName("WINWORD")) {
p.Kill();
}
File.Copy(TemplateFile1, temppath,true);
doc = new Microsoft.Office.Interop.Word.Document();
app = new Microsoft.Office.Interop.Word.Application();
//模板路径
string TemplateFile = temppath;
object Obj_FileName = temppath;
object Visible = false;
object ReadOnly = false;
object missing = System.Reflection.Missing.Value;
//C#操作Word书签
//打开文件
doc = app.Documents.Open(ref Obj_FileName,
ref missing, ref ReadOnly, ref missing,
ref missing, ref missing, ref missing, ref missing,
ref missing, ref missing, ref missing, ref Visible,
ref missing, ref missing, ref missing,
ref missing);
doc.Activate();
//标签
object bookMark = "";
if (app.ActiveDocument.Bookmarks.Exists("RQ") == true) {
bookMark = "RQ";
app.ActiveDocument.Bookmarks.get_Item
(ref bookMark).Range.Text = this.textBox1.Text;
}
if (app.ActiveDocument.Bookmarks.Exists("BZ") == true) {
bookMark = "BZ";
app.ActiveDocument.Bookmarks.get_Item
(ref bookMark).Range.Text = this.textBox2.Text;
}
//C#操作Word书签
object IsSave = true;
doc.Close(ref IsSave, ref missing, ref missing);
SaveFileDialog _save = new SaveFileDialog();
_save.InitialDirectory = "C:\\";
_save.Filter = "*.doc|*.*";
_save.FileName = "新建文档.doc";
if (_save.ShowDialog() == DialogResult.OK) {
SaveAS(_save.FileName);
}
}
/// <summary>
/// 文档另存为
/// </summary>
/// <param name="FileName">保存的文件名名称</param>
/// <returns></returns>
public bool SaveAS(string FileName) {
bool _bool = false;
try {
//模板路径
string TemplateFile = temppath;
//生成word文档
string FileName1 = FileName;
File.Copy(TemplateFile, FileName);
_bool = true;
return _bool;
} catch {
return _bool;
}
}
}
}