上一篇文档中,先对模板进行了设置,然后利用OfficeIntegration包对模板进行了调用,并输出相应的数据。本文在此基础上进一步对WORD进行了表格合并功能的操作,但还有一些功能进行尝试中。
partial void GenerateDocument_Execute()
{
// Write your code here.
string path= Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
Assembly ass = Assembly.GetExecutingAssembly();
Stream s = ass.GetManifestResourceStream(this.GetType(), "MonthPlan.docx");
byte[] bt = new byte[s.Length];
s.Read(bt, 0, bt.Length);
s.Close();
s.Dispose();
var fileName = this.WorkPlanHeads.SelectedItem.PlanYearMonth + "工作计划";
FileStream fs = new FileStream(path + "\\"+fileName+".docx", FileMode.Create);
fs.Write(bt, 0, bt.Length);
fs.Close();
fs.Dispose();
List<OfficeIntegration.ColumnMapping> planHeadColumn = new List<ColumnMapping>() {
new ColumnMapping("PlanYear","PlanYear"),
new ColumnMapping("PlanMonth","PlanMonth"),
new ColumnMapping("FillDate","FillDate")
};
dynamic doc = OfficeIntegration.Word.GenerateDocument(path + "\\"+ fileName+".docx", this.WorkPlanHeads.SelectedItem, planHeadColumn);
List<string> detailsHeader = new List<string>() {
"" ,"TypeName","PlanContent","WorkEmp","WorkDept","PlanEndDate","Remark"
};
OfficeIntegration.Word.ExportEntityCollection(doc, "PlanDetail", 2, false, this.WorkPlanHeads.SelectedItem.WorkPlanDetails, detailsHeader);
// OfficeIntegration.Word.SaveAsPDF(doc, path + "\\" + fileName + ".pdf", true);
string preStr="",curStr="";
int indexStart = 2, indexEnd = 2; //VBA索引从1开始+标题列
var table = doc.Tables(1); //模板中第一个表
for (int i = 2; i < table.Rows.Count+1; i++)
{
curStr = doc.Tables(1).Cell(i, 2).Range.Text;//取出表格中的数据,也可利用数据源来做
if (curStr == preStr)
{
indexEnd = i;
table.Cell(i - 1, 2).Range.Text = "";//合并单元格内容删除
if (i == table.Rows.Count)
{
if (indexEnd > indexStart)
table.Cell(indexStart, 2).Merge(table.Cell(indexEnd, 2));
}
}
else
{
if (indexEnd > indexStart)
table.Cell(indexStart,2).Merge(table.Cell(indexEnd,2));
indexStart = i;
}
preStr = curStr;
}
doc.Save();//直接保存文档
}
原本考虑用VBA,在模板文档里执行合并的操作。但考虑到安全性问题,放弃了这种做法。直接用dynamic 来操作客户端WORD。
目前还需要解决的问题是输出的日期格式,一种方法是在数据源里就格式化成自己想要的格式(字符类型),另一种只能在模板里再想想办法了。
效果如下图