前几天工作中上交的文档被认证方要求文档表格统一加两行信息,文档比较多,使用的又是统一模板,偷了点懒,写了个小程序自动加入,开始用NPOI做的,网上可以找到教程,接口也比较清晰,还是比较顺利的,但后来发现编辑完保存的文件里viso图丢失了。。空欢喜一场。。后来又试了几个插件,最终Docx实现的,开源,在GitHub可以找到源码,有兴趣的可以看一下。说完废话,直接贴代码。
private void btn_openfile_Click(object sender, EventArgs e)
{
var openFileDialog = new System.Windows.Forms.OpenFileDialog();
openFileDialog.Filter = "(*.docx)|*.docx|(*.doc)|*.doc";
openFileDialog.RestoreDirectory = true;
openFileDialog.FilterIndex = 1;
DialogResult result = openFileDialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
txt_filepath.Text = openFileDialog.FileName;
}
}
private void btn_InsertInfo_Click(object sender, EventArgs e)
{
var sourcePath = txt_filepath.Text;
if (File.Exists(sourcePath))
{
try
{
//加载文件
var doc = DocX.Load(sourcePath);
//遍历文中表格
foreach (var table in doc.Tables)
{
//查找插入位置
int i = 0;
for (i = 0; i < table.Rows.Count; i++)
{
if (table.Rows[i].Cells[0]?.Paragraphs[0]?.Text == "函数参数")
{
break;
}
}
if (i < table.Rows.Count)
{
//设置字体 加粗 字号
Formatting fmt = new Formatting();
fmt.Bold = true;
fmt.Size = 9;
//插入一行
var row1 = table.InsertRow(i+2);
//合并水平方向单元格
row1.MergeCells(1, 2);
//设置单元格背景颜色
row1.Cells[0].FillColor = table.Rows[i].Cells[0].FillColor;
//设置单元格紫婷
row1.Cells[0].Paragraphs[0].Font("宋体");
//设置单元格内容
row1.Cells[0].Paragraphs[0].Append("全局变量", fmt);
row1.Cells[1].FillColor = table.Rows[i].Cells[1].FillColor;
row1.Cells[1].Paragraphs[0].Font("宋体");
row1.Cells[1].Paragraphs[0].Append("变量名称:变量类型;说明;取值范围", fmt);
Formatting fmt1 = new Formatting();
fmt1.Bold = false;
fmt1.Size = 9;
var row2 = table.InsertRow(i+3);
row2.MergeCells(1, 2);
row2.Cells[1].Paragraphs[0].Font("宋体");
row2.Cells[1].Paragraphs[0].Append("N/A", fmt1);
//合并垂直方向单元格
table.MergeCellsInColumn(0, i+2,i+3 );
//设置单元内容位置
row1.Cells[0].Paragraphs[0].Alignment = Alignment.center;
row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
}
}
//写入新文件
var destPath = sourcePath.Insert(sourcePath.LastIndexOf('.'), "_全局变量默认");
if (File.Exists(destPath))
File.Delete(destPath);
doc.SaveAs(destPath);
MessageBox.Show("插入完成");
}
catch (Exception ex)
{
MessageBox.Show("插入失败,请确认文档已关闭!");
}
}
else
{
MessageBox.Show("请选择有效文件!");
}
}