首先是借鉴的这位大佬的博客:C#操作Word,写数据,插入图片 - Sealee - 博客园
要将Aspose.Words.dll文件放在unity工程中的Plugins文件夹下,并在工程中引入
在word中新建书签与表格
private string filePath;
private string filePathColne;
private string imagePath; //图片路径
private Document doc;
private DocumentBuilder builder;
private string tempStr;
void Start()
{
tempStr = "D:\\PrintImage/20210922151659.jpg";
imagePath = null;
filePath = "D:\\PrintWord/PrintWord.doc";
filePathColne = "D:\\PrintWord/PrintWordColbe.doc";
File.Copy(filePath, filePathColne, true); //必须复制一个word出来,不然会报错
File.SetAttributes(filePathColne, FileAttributes.Normal); //设置复制出来的文件的属性 只读 还是可修改
doc = new Document(filePathColne);
}
private void WriteImage(string imgPath)
{
builder = new DocumentBuilder(doc);
builder.MoveToBookmark("img"); //定位img书签的位置,(大佬博客中的说法),我试着删除书签后,结果是直接在word第一行中插入图片
FileStream fs = new FileStream(imgPath, FileMode.Open); //读取图片,并以byte[]的方式写入
byte[] imageByte = new byte[fs.Length];
fs.Read(imageByte, 0, imageByte.Length);
builder.InsertImage(imageByte, 400, 400);
fs.Close();
WriteExcel();//调用插入表格数据的方法
builder = null;
doc.Save(filePathColne);
}
private void WriteExcel()
{
NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获取所有表格
Table table = allTables[0] as Table; //获取第一个表格
var row = table.Rows[table.Rows.Count - 1]; //在表格的最后一行插入数据
builder.MoveToCell(0, table.Rows.Count - 1, 0, 0); //移动到单元格第几行第几列
builder.Write("菜鸡"); //写入数据
builder.MoveToCell(0, table.Rows.Count - 1, 1, 0);
builder.Write("菜鸡");
builder.MoveToCell(0, table.Rows.Count - 1, 2, 0);
builder.Write("菜鸡");
builder.MoveToCell(0, table.Rows.Count - 1, 3, 0);
builder.Write("菜鸡");
builder.MoveToCell(0, table.Rows.Count - 1, 4, 0);
builder.Write("菜鸡");
builder.MoveToCell(0, table.Rows.Count - 1, 5, 0);
builder.Write("菜鸡");
builder.MoveToCell(0, table.Rows.Count - 1, 6, 0);
builder.Write("菜鸡");
}
void Update()
{
if (Input.GetKeyDown(KeyCode.O))
{
WriteImage(tempStr);
}
}
这个是效果图
?Aspose.Words.dll文件可以在网上搜索下载
|