1.首先要引用Aspose.Words和Aspose.Cells,最好是最新版本
2.把WORD文档需要插入单个数据的地方添加书签。表格暂时不用添加书签。
3.创建新文件夹以及下载其他附件等问题,请参考之前文章C# 复制文件并下载。
4.读取需要插入WORD文档。 sourceFileWORD文档所在文件夹路径。newFolderPath是要写入数据后保存的文件路径,不包含文件名称。
string[] FileList = Directory.GetFiles(sourceFile);
5.循环WORD文档,并进行数据写入(假设我们的数据源是表dt):
foreach (string file in BankFileList)
{
//获取文件路径及其名称,因为不同的文档需要插入不同的数据
string fileName = System.IO.Path.GetFileName(file); fileName = fileName.Substring(0, fileName.IndexOf("."));
//word文档
if (file.Contains("doc") || file.Contains("docx"))
{
Document doc = new Document(file);
DocumentBuilder builder = new DocumentBuilder(doc);
Aspose.Words.NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true);
Aspose.Words.Tables.Table table;//声明一个表格,以供后续使用
//开始写入数据
if (fileName == "XXXXX")
{
table = allTables[0] as Aspose.Words.Tables.Table;//读取表格
Aspose.Words.Tables.Row rowTen = table.Rows[9];//获取插入数据的上一行数据。因为一般表格都会有一个标题等
//添加每行数据
int rowIndex = 9;//从第9行开始添加
for (int i = 0; i < dt.Rows.Count; i++)
{
//复制表头的那行样式和数据等过来。如果你单独插入一行,你自己试试吧会有惊喜的
Aspose.Words.Tables.Row row = (Aspose.Words.Tables.Row)rowTen.Clone(true);
//因为复制的是表头,所以里面的数据是需要我们根据实际数据替换掉的。更改序号
Aspose.Words.Tables.Cell cell = row.Cells[0];
Aspose.Words.Paragraph p = new Paragraph(doc);
p.AppendChild(new Run(doc, (i + 1).ToString()));
cell.FirstParagraph.Remove();//移除之前的数据
cell.AppendChild(p);
//更改为需要填充的数据=XXX
string str1 = dt.Rows[i]["XXX"].ToString();
cell = row.Cells[1];
p = new Paragraph(doc);
p.AppendChild(new Run(doc, str1));
cell.FirstParagraph.Remove();
cell.AppendChild(p);
//数据更改完毕
table.Rows.Insert(rowIndex, row); //将此行插入第一行的上方
rowIndex++;
}
table.Rows.Remove(rowTen);//这一句根据实际情况来是否需要。有的表格下面有一行空的,有的没有。
//需要替换书签的数据
var dic = new Dictionary<string, string>();
dic.Add("书签名称1", 数据1);
dic.Add("书签名称2", 数据2);
//书签替换
foreach (var key in dic.Keys)
{
builder.MoveToBookmark(key);
builder.Write(dic[key]);
}
}
//然后保存,记得一定要是DOCX后缀。你可以试试DOC后缀。
doc.Save(Path.Combine(newFolderPath, fileName + ".docx"));
}
//EXCEL的插入
else if (file.Contains("xlsx") || file.Contains("xls"))
{
Workbook excel = new Workbook();
excel.Open(file); Worksheet sheet = excel.Worksheets["Sheet1"];
if (fileName == "中行电票内容")
{
sheet = excel.Worksheets["实际EXCEL里面的需要插入的表名"];
//这里是对具体的不是表格的单元格进行写数.如果是合并单元格,只能是合并单元格的第一个单元格才能写入数据。这里注意:必须根据顺序按行列顺序插入,否则可能写入不成功。
sheet.Cells[rowIndex + 1, 3].PutValue(数据1);
sheet.Cells[rowIndex + 1, 5].PutValue(数据2);
int rowIndex = 5;//从第几行插入,插入在下方
for (int i = 0; i < dt.Rows.Count; i++)
{
sheet.Cells.InsertRows(rowIndex, 1);
sheet.Cells[rowIndex, 0].PutValue(i + 1);
//一般写法
sheet.Cells[rowIndex, 1].PutValue(dt.Rows[i]["字段名"].ToString());
//金额有样式的写法
sheet.Cells[rowIndex, 5].PutValue(String.Format("{0:N}", dt.Rows[i]["字段名"].ToString()));
sheet.Cells[rowIndex, 5].SetStyle(new Aspose.Cells.Style { HorizontalAlignment = Aspose.Cells.TextAlignmentType.Right });
rowIndex++;
}
}
excel.Save(Path.Combine(newFolderPath, fileName + ".xlsx"));
}
}