前言
最近(2019-05-12写)因为同事发现已经交付的项目,在Word转Pdf后图片不清晰(是因为在Word中插入图片就不太清晰),因为涉及到签名(CA)之类,所以只能写Demo去做测试.项目中是使用Office自带的Microsoft.Office.Interop,最终项目中是使用Office组件动态创建表格,调整图片大小,便想尝试用Aspose.Words该怎么实现动态表格,并填充内容.表格是根据图片数来动态创建表格的行数和列数.分3*3 3*4 4*4 4*5,表格又分图片和内容,图片和内容是对应的.行数要乘以2,列数不变.表格是根据图片数来动态创建表格的行数和列数.分3*3 3*4 4*4 4*5,表格又分图片和内容,图片和内容是对应的.行数要乘以2,列数不变.
使用Aspose.Words组件实现
static void Main(string[] args){List imageList = new List();for (int i = 0; i < 9; i){imageList.Add(#34;{i1}.bmp");}int rows = 0, cols = 0;double width = 0f, height = 0f;int imgCount = imageList.Count;if (imgCount <= 9){rows = 6;cols = 3;width = 160f;height = 140f;}else{if (imgCount <= 12){rows = 6;cols = 4;width = 106.7f;height = 115f;}else if (imgCount <= 16){rows = 8;cols = 4;width = 92.5f;height = 92.5f;}else{rows = 8;cols = 5;width = 83.5f;height = 84f;}}//1. 读取word文档Document doc = new Document("test.doc");//2. 根据书签,定位在哪里创建表格DocumentBuilder builder = new DocumentBuilder(doc);builder.MoveToBookmark("newLine");//3. 创建tablebuilder.StartTable();builder.CellFormat.Width = 480;builder.CellFormat.Borders.LineStyle = LineStyle.None;//去除边框int index = 0;int contentIndex = 0;for (int i = 0; i < rows; i){if (i % 2 == 0){//奇数行,插入图片for (int j = 0; j < cols; j){builder.InsertCell();//创建单元格builder.InsertImage(imageList[index], width, height);index;}}else{//偶数行,插入内容for (int j = 0; j < cols; j){builder.InsertCell();builder.Write(Path.GetFileNameWithoutExtension(imageList[contentIndex]));contentIndex;}}builder.EndRow();//行结束}builder.EndTable();//结束tabledoc.Save(#34;{Guid.NewGuid().ToString()}.docx", SaveFormat.Docx);Console.ReadKey();}改进
因为对Aspose.Words使用少,在查过API之后,发现有MoveToCell,对上面代码稍作调整.【C#如何在Word中动态创建表格】
//根据行数和列数,创建表格所有的单元格for (int i = 0; i < rows; i){for (int j = 0; j < cols; j){builder.InsertCell();}builder.EndRow();}//填充单元格内容for (int i = 0; i < rows / 2; i){for (int j = 0; j < cols; j){int rowNum = i * 2;builder.MoveToCell(0, rowNum, j, 0);//奇数行builder.InsertImage(imageList[index], width, height);builder.MoveToCell(0, rowNum1, j, 0); //偶数行builder.Write(Path.GetFileNameWithoutExtension(imageList[contentIndex]));}}