先定义一个WORD 模板, 然后替换文本、域 ,定位开始表格

文本和段落

                // Specify font formattingAspose.Words.Font font = builder.Font;font.Size = 16;font.Bold = true; ;font.Color = Color.Black;font.Name ="Arial";font.Underline=Underline.Dash;//builder.Write("Sample text."); //插入文本// Specify paragraph formattingParagraphFormat paragraphFormat = builder.ParagraphFormat;paragraphFormat.FirstLineIndent = 8;paragraphFormat.Alignment = ParagraphAlignment.Justify;paragraphFormat.KeepTogether= true;builder.Writeln("A whole paragraph.");  //插入一段文本(需要加格式的ParagraphFormat)

View Code

                    //Specify paragraph formattingParagraphFormat paragraphFormat = builder.ParagraphFormat;paragraphFormat.FirstLineIndent = 24;//paragraphFormat.Alignment = ParagraphAlignment.Justify;//paragraphFormat.KeepTogether = true;Aspose.Words.Font font = builder.Font;InSertText(builder, i + "、我在", 12, "仿宋", false);InSertText(builder, item["期数"].ToString(), 12, "仿宋", true);InSertText(builder, "资金清算账户于", 12, "仿宋", false);InSertText(builder, Convert.ToDateTime(item["资金垫付日期"]).ToString("yyyy年MM月dd日"), 12, "仿宋", true);InSertText(builder, "元为偿还第", 12, "仿宋", false);InSertText(builder, item["垫付期数"].ToString(), 12, "仿宋", true);InSertText(builder, "期的款项;", 12, "仿宋", false);builder.Writeln();  //插入段落文本/// <summary>/// 插入文本/// </summary>/// <param name="builder"></param>/// <param name="strText"></param>/// <param name="size"></param>/// <param name="fontName"></param>/// <param name="isUnderline"></param>/// <param name="bold"></param>private void InSertText(DocumentBuilder builder, string strText, int size = 12,string fontName = "仿宋", bool isUnderline = false, bool bold = false){Aspose.Words.Font font = builder.Font;font.Size = size;font.Bold = bold; ;font.Color = Color.Black;font.Name = fontName;if (isUnderline){font.Underline = Underline.Single;}builder.Write(strText);font.ClearFormatting();}            

View Code

单元格

        /// <summary>/// 添加单元格/// </summary>/// <param name="builder"></param>/// <param name="data"></param>/// <param name="width"></param>public static void InsertCell(DocumentBuilder builder, string data, double width){builder.InsertCell();builder.RowFormat.Height = 22;builder.CellFormat.Width = width;builder.CellFormat.Borders.LineStyle = LineStyle.Single;builder.CellFormat.Borders.Color = System.Drawing.Color.Black;builder.CellFormat.VerticalMerge = CellMerge.None;builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中builder.Font.Size = 8;//builder.Font.Bold = true;
            builder.Write(data);}

View Code

图片单元格

        /// <summary>/// 添加带图片的单元格/// </summary>/// <param name="doc">word文档</param>/// <param name="builder"></param>/// <param name="strUrl">图片路径</param>/// <param name="width">单元格宽度</param>/// <param name="height">单元格高度</param>/// <param name="tableIndex">表索引</param>/// <param name="rowIndex">行索引</param>/// <param name="columnIndex">列索引</param>private static void InsertCellWithImage(Document doc, DocumentBuilder builder, string strUrl, double width, double height, int rowIndex, int columnIndex){builder.InsertCell();builder.RowFormat.Height = height;builder.CellFormat.Width = width;builder.CellFormat.Borders.LineStyle = LineStyle.Single;builder.CellFormat.Borders.Color = System.Drawing.Color.Black;builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;    // 垂直居中builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;  // 水平居中if (File.Exists(HttpContext.Current.Server.MapPath(strUrl))){// 向此单元格中插入图片Shape shape = new Shape(doc, ShapeType.Image);shape.ImageData.SetImage(HttpContext.Current.Server.MapPath(strUrl));shape.Width = width - 5;shape.Height = height-5;shape.HorizontalAlignment = HorizontalAlignment.Center;shape.VerticalAlignment = VerticalAlignment.Center;builder.InsertNode(shape);}}

View Code

表格--书签位置

            DocumentBuilder builder = new DocumentBuilder(doc);            builder.MoveToBookmark("table"); //移动到书签
            builder.StartTable();builder.CellFormat.Shading.BackgroundPatternColor = Color.Yellow;InsertCell(builder, "测试", 235);builder.EndRow();builder.CellFormat.Shading.BackgroundPatternColor = Color.White;builder.EndTable();            

View Code

替换:  插入-文本部件-域

            string[] fieldNames = {  "Test01","Test02"};object[] fieldValues = {  "Test01","Test02"};fieldValues[0]="测试01";fieldValues[1]="测试02";            

View Code

            doc.MailMerge.Execute(fieldNames, fieldValues);doc.MailMerge.DeleteFields();  string strPhysicsPath = HttpContext.Current.Server.MapPath(DocPath);if (!Directory.Exists(strPhysicsPath)){Directory.CreateDirectory(strPhysicsPath);}string tempUrl = "/" + strProjName + filename + ".doc";strPhysicsPath = strPhysicsPath.TrimEnd('\\') + tempUrl;if (Directory.Exists(strPhysicsPath)){File.Delete(strPhysicsPath);}doc.Save(strPhysicsPath, SaveFormat.Docx);return  tempUrl;              

View Code

            filepath = "~/Config/Template/" + filepath;Document doc = new Document(HttpContext.Current.Server.MapPath(filepath));DocumentBuilder builder = new DocumentBuilder(doc);var dicData = new Dictionary<string, object>();PropertyInfo[] pros = data.GetType().GetProperties();foreach (var pro in pros){dicData.Add(pro.Name, pro.GetValue(data));}var lstCheckReportQuestion = (List<TCheckReportQuestion>)dicData["checkquest"];var lstQualityQuestion = lstCheckReportQuestion.FindAll(c => c.QuestType == "1");       // 质量问题var lstSecurityQuestion = lstCheckReportQuestion.FindAll(c => c.QuestType == "2");      // 安全文明问题#region 1:域  “插入” →“文档部件”→“域”→“MergeField”//“插入” →“文档部件”→“域”→“MergeField”//表格2种方法:1.域,表格主要是注意tablestart和tableend,标题不用插入域,只需在下一行定义好域即可;  第一列《TableStart:arrangeList(数据数组)》《Id》     最后一列《name》《TableEnd:arrangeList(数据数组)》 //在循环的列表下添加列表的起始和结束域: << TableStart:RawMaterialList >> 和 << TableEnd:RawMaterialList >> 以及列表中的各项域.//2.域《Quality》,表格:builder.MoveToBookmark("Quality"); Table tableQ = builder.StartTable();// 绘制质量风险问题表builder.MoveToBookmark("Quality");Table tableQ = builder.StartTable();double height = 60;int rowIndex = 0;lstQualityQuestion.ForEach(p =>{InsertCellWithImage(doc, builder, p.MiniImgUrl, 100, height, rowIndex, 0);InsertCell(builder, p.QuestDesc, p.CorrectWay, 200, height, 10);rowIndex++;builder.EndRow();});if (tableQ.FirstRow != null){tableQ.AllowAutoFit = false;}builder.EndTable();// 绘制安全文明问题表builder.MoveToBookmark("Security");Table tableS = builder.StartTable();rowIndex = 0;lstSecurityQuestion.ForEach(p =>{InsertCellWithImage(doc, builder, p.MiniImgUrl, 100, height, rowIndex, 0);InsertCell(builder, p.QuestDesc, p.CorrectWay, 200, height, 10);rowIndex++;builder.EndRow();});if (tableS.FirstRow != null){tableS.AllowAutoFit = false;}builder.EndTable();string[] fieldNames = new string[] { "ProjectName", "CreateTime", "ConstruStage", "CheckTime", "InspectLeader", "InspectMember", "ComEvaluation", "FeedBack", "Advice", "InstitutionManage", "InspectProgress", "Description", "Email", "Signature", "SignDate" };object[] fieldValues = new object[] { "ProjectName", "CreateTime", "ConstruStage", "CheckTime", "InspectLeader", "InspectMember", "ComEvaluation", "FeedBack", "Advice", "InstitutionManage", "InspectProgress", "Description", "Email", "Signature", "SignDate" };for (int i = 0; i < fieldValues.Length; i++){fieldValues[i] = dicData[fieldValues[i].ToString().ToLower()];}#endregion#region 2:书签  “插入” →“书签”//书签的局限性在于:一个word文档里只有一个书签,不能同名//for (int k = 0; k < fieldNames.Length; k++)//{//    if (doc.Range.Bookmarks[fieldNames[k].ToString()] != null)//    {//        doc.Range.Bookmarks[fieldNames[k].ToString()].Text = fieldValues[k].ToString();//    }//}#endregiondoc.MailMerge.Execute(fieldNames, fieldValues);doc.MailMerge.DeleteFields();   //清除doc.Range.Bookmarks.Clear();    //清除string strPhysicsPath = HttpContext.Current.Server.MapPath(Config.AccPath + "Temp/Export");if (!Directory.Exists(strPhysicsPath)){Directory.CreateDirectory(strPhysicsPath);}string tempUrl = string.Format("/{0}项目{1}报告.doc", dicData["projectname"], dicData["checktime"]);strPhysicsPath = strPhysicsPath.TrimEnd('\\') + tempUrl;if (File.Exists(strPhysicsPath)){File.Delete(strPhysicsPath);}doc.Save(strPhysicsPath, SaveFormat.Docx);return Config.AccPath.Replace("~", "") + "Temp/Export" + tempUrl;

View Code

---以上用过的

         /// <summary>/// 设置打开密码/// </summary>/// <param name="pwd"></param>public void SetPassword(string pwd){WordDoc.Protect(ProtectionType.ReadOnly, pwd);}/// <summary>/// 不可编辑受保护,需输入密码/// </summary>/// <param name="Password"></param>public void NoEdit(string Password){WordDoc.Protect(ProtectionType.ReadOnly, Password);}

View Code

https://www.cnblogs.com/birchlee/archive/2013/05/23/3094632.html

https://blog.csdn.net/spt_dream/article/details/79664155

https://www.cnblogs.com/seejoy/p/6847570.html 有DLL下载

https://www.cnblogs.com/ariter/p/5948597.html

导出表格数据–获取表格对象方法一

//数据行开始的索引  从第二行开始插入数据
int intRowIndex = 1;
//获取表格对象 获取文档中的第一个表格
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
//复制并添加行
table.Rows.Insert(intRowIndex, table.LastRow.Clone(true));
//对表格进行赋值
builder.MoveToCell(0, intRowIndex, 0, 0);
builder.Write("填充数据");
builder.MoveToCell(0, intRowIndex, 1, 0);
builder.Write("填充数据");
//去除最后的空行
if (table != null)
{table.LastRow.Remove();
}

View Code

导出表格数据–获取表格对象方法二

NodeCollection allTables = doc.GetChildNodes(NodeType.Table, true); //获得word中的所有表格
Table table1 = allTables[1] as Aspose.Words.Tables.Table;  //取到第二个表
DocumentBuilder builder = new DocumentBuilder(doc);int rowsNum = 0;  //插入数据开始行
builder.MoveTo(table1.Rows[rowsNum].Cells[0].Paragraphs[0]);
builder.Write(Num.ToString());                                  builder.MoveTo(table1.Rows[rowsNum].Cells[1].Paragraphs[0]);
builder.Write("值"); 

View Code

一段清除html格式的方法

public static string NoHTML(string Htmlstring){if (Htmlstring.Length > 0){//删除脚本Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);//删除HTMLHtmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);Htmlstring = Regex.Replace(Htmlstring, @"&ldquo;", "\"", RegexOptions.IgnoreCase);//保留【 “ 】的标点符合Htmlstring = Regex.Replace(Htmlstring, @"&rdquo;", "\"", RegexOptions.IgnoreCase);//保留【 ” 】的标点符合Htmlstring.Replace("<", "");Htmlstring.Replace(">", "");Htmlstring.Replace("\r\n", "");Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();}return Htmlstring;}

View Code

用Aspose.Words把word转成图片

Document doc = new Document("f:\\333.doc");
ImageSaveOptions iso = new          ImageSaveOptions(SaveFormat.Jpeg);
iso.Resolution = 128;
iso.PrettyFormat = true;
iso.UseAntiAliasing = true;
for (int i = 0; i < doc.PageCount; i++)
{iso.PageIndex = i;doc.Save("D:/test/test" + i + ".jpg", iso);
}

View Code

使用 Microsoft.Office.Interop.Word  --用过的

public class ExportWord{private Application wordApp = null;private Document wordDoc = null;public Application Application{get{return wordApp;}set{wordApp = value;}}public Document Document{get{return wordDoc;}set{wordDoc = value;}}//通过模板创建新文档public void CreateNewDocument(string filePath){killWinWordProcess();wordApp = new Application();//ApplicationClass此类不被识别请看下列问题对应的解决方法wordApp.DisplayAlerts = WdAlertLevel.wdAlertsNone;wordApp.Visible = false;object missing = System.Reflection.Missing.Value;object templateName = filePath;//--也可以//wordDoc = wordApp.Documents.Open(ref templateName, ref missing,//  ref missing, ref missing, ref missing, ref missing, ref missing,//  ref missing, ref missing, ref missing, ref missing, ref missing,//  ref missing, ref missing, ref missing, ref missing);object objDocType = WdDocumentType.wdTypeDocument;object objfalse = false;object objtrue = true;wordDoc = wordApp.Documents.Add(ref templateName, ref objfalse, ref objDocType, ref objtrue);}//保存新文件public void SaveDocument(string filePath){object fileName = filePath;object format = WdSaveFormat.wdFormatDocument;//保存格式object miss = System.Reflection.Missing.Value;wordDoc.SaveAs(ref fileName, ref format, ref miss,ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss,ref miss);//关闭wordDoc,wordApp对象object SaveChanges = WdSaveOptions.wdSaveChanges;object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;object RouteDocument = false;wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); //关闭Word进程
        }/// <summary>/// 关闭wordDoc,wordApp对象/// </summary>private void DisposeWord(){object SaveChanges = WdSaveOptions.wdSaveChanges;object OriginalFormat = WdOriginalFormat.wdOriginalDocumentFormat;object RouteDocument = false;wordDoc.Close(ref SaveChanges, ref OriginalFormat, ref RouteDocument);wordApp.Quit(ref SaveChanges, ref OriginalFormat, ref RouteDocument); //关闭Word进程
        }//在书签处插入值public bool InsertValue(string bookmark, string value){object bkObj = bookmark;if (wordApp.ActiveDocument.Bookmarks.Exists(bookmark)){wordApp.ActiveDocument.Bookmarks.get_Item(ref bkObj).Select();wordApp.Selection.TypeText(value);return true;}return false;}//插入表格,bookmark书签public Table InsertTable(string bookmark, int rows, int columns, float width){object miss = System.Reflection.Missing.Value;object oStart = bookmark;//Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置// Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置// wordApp.Selection.EndKey(6, 0);
            wordApp.Selection.EndKey(WdUnits.wdStory);wordApp.Selection.InsertNewPage();//object start = 0;//object end = 0;//Range tableLocation = wordDoc.Range(ref start, ref end);
Table newTable = wordDoc.Tables.Add(wordApp.Selection.Range, rows, columns, ref miss, ref miss);//设置表的格式newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度if (width != 0){newTable.PreferredWidth = width;//表格宽度
            }newTable.AllowPageBreaks = false;//object oMissing = System.Reflection.Missing.Value;//wordApp.Visible = true;//wordDoc = wordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);//object start = 0;//object end = 0;//Microsoft.Office.Interop.Word.Range tableLocation = wordDoc.Range(ref start, ref end);//Table newTable = wordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing);return newTable;}/// <summary>/// 添加一个新表 参考/// </summary>public Table AddTable(int rows, int columns){object oMissing = System.Reflection.Missing.Value;Microsoft.Office.Interop.Word.Application WordApp;Microsoft.Office.Interop.Word.Document WordDoc;WordApp = new Microsoft.Office.Interop.Word.Application();WordApp.Visible = true;WordDoc = WordApp.Documents.Add(ref oMissing, ref oMissing, ref oMissing, ref oMissing);object start = 0;object end = 0;Microsoft.Office.Interop.Word.Range tableLocation = WordDoc.Range(ref start, ref end);Table newTable = WordDoc.Tables.Add(tableLocation, rows, columns, ref oMissing, ref oMissing);//3行4列的表//设置表的格式newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度newTable.AllowPageBreaks = false;return newTable;}//合并单元格 表名,开始行号,开始列号,结束行号,结束列号public void MergeCell(Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2){table.Cell(row1, column1).Merge(table.Cell(row2, column2));}//设置表格内容对齐方式Align水平方向,Vertical垂直方向(左对齐,居中对齐,右对齐分别对应Align和Vertical的值为-1,0,1)public void SetParagraph_Table(Microsoft.Office.Interop.Word.Table table, int Align, int Vertical){switch (Align){case -1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphLeft; break;//左对齐case 0: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter; break;//水平居中case 1: table.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphRight; break;//右对齐
            }switch (Vertical){case -1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalTop; break;//顶端对齐case 0: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalCenter; break;//垂直居中case 1: table.Range.Cells.VerticalAlignment = WdCellVerticalAlignment.wdCellAlignVerticalBottom; break;//底端对齐
            }}//设置表格字体public void SetFont_Table(Microsoft.Office.Interop.Word.Table table, string fontName, double size){if (size != 0){table.Range.Font.Size = Convert.ToSingle(size);}if (fontName != ""){table.Range.Font.Name = fontName;}}//是否使用边框,n表格的序号,use是或否public void UseBorder(int n, bool use){if (use){wordDoc.Content.Tables[n].Borders.Enable = 1; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
            }else{wordDoc.Content.Tables[n].Borders.Enable = 2; //允许有边框,默认没有边框(为0时无边框,1为实线边框,2、3为虚线边框,以后的数字没试过)
            }}//给表格插入一行,n表格的序号从1开始记public void AddRow(int n){object miss = System.Reflection.Missing.Value;wordDoc.Content.Tables[n].Rows.Add(ref miss);wordDoc.Content.Tables[n].Rows.Height = 100;//设置新增加的这行表格的高度
        }//给表格添加一行public void AddRow(Microsoft.Office.Interop.Word.Table table){object miss = System.Reflection.Missing.Value;table.Rows.Height = 40;table.Rows.Add(ref miss);}//给表格插入rows行,n为表格的序号public void AddRow(int n, int rows){object miss = System.Reflection.Missing.Value;Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];for (int i = 0; i < rows; i++){table.Rows.Add(ref miss);}}//给表格中单元格插入元素,table所在表格,row行号,column列号,value插入的元素public void InsertCell(Microsoft.Office.Interop.Word.Table table, int row, int column, string value){table.Cell(row, column).Range.Text = value;}//给表格中单元格插入元素,n表格的序号从1开始记,row行号,column列号,value插入的元素public void InsertCell(int n, int row, int column, string value){wordDoc.Content.Tables[n].Cell(row, column).Range.Text = value;}//给表格插入一行数据,n为表格的序号,row行号,columns列数,values插入的值public void InsertCell(int n, int row, int columns, string[] values){Microsoft.Office.Interop.Word.Table table = wordDoc.Content.Tables[n];for (int i = 0; i < columns; i++){table.Cell(row, i + 1).Range.Text = values[i];}}//插入图片public void InsertPicture(string bookmark, string picturePath, float width, float hight){object miss = System.Reflection.Missing.Value;object oStart = bookmark;Object linkToFile = false;    //图片是否为外部链接Object saveWithDocument = true; //图片是否随文档一起保存object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//图片插入位置wordDoc.InlineShapes.AddPicture(picturePath, ref linkToFile, ref saveWithDocument, ref range);wordDoc.Application.ActiveDocument.InlineShapes[1].Width = width; //设置图片宽度wordDoc.Application.ActiveDocument.InlineShapes[1].Height = hight; //设置图片高度
        }//插入一段文字,text为文字内容public void InsertText(string bookmark, string text){object oStart = bookmark;object range = wordDoc.Bookmarks.get_Item(ref oStart).Range;Paragraph wp = wordDoc.Content.Paragraphs.Add(ref range);wp.Format.SpaceBefore = 6;wp.Range.Text = text;wp.Format.SpaceAfter = 24;wp.Range.InsertParagraphAfter();wordDoc.Paragraphs.Last.Range.Text = "\n";}//杀掉winword.exe进程public void killWinWordProcess(){System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("WINWORD");foreach (System.Diagnostics.Process process in processes){bool b = process.MainWindowTitle == "";if (process.MainWindowTitle == ""){process.Kill();}}}public static bool ExportLoanLawyersLetter(){//生成WORD程序对象和WORD文档对象Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();Microsoft.Office.Interop.Word.Document doc = new Document();object miss = System.Reflection.Missing.Value;try{//打开模板文档,并指定doc的文档类型//object objTemplate = System.Windows.Forms.Application.StartupPath + @"\UploadFiles\tz103.doc";//路径一定要正确object objTemplate = @"d:\\敢贷律师函模板.doc";object objDocType = WdDocumentType.wdTypeDocument;object objfalse = false;object objtrue = true;doc = (Document)appWord.Documents.Add(ref objTemplate, ref objfalse, ref objDocType, ref objtrue);//获取模板中所有的书签Bookmarks odf = doc.Bookmarks;string[] testTableremarks = { "CustName", "GenderName", "LoanDate", "ContractName","LoanAmount", "Periods", "MonthSupply", "RepaymentPeriod", "Periods2", "Month", "Day", "UnSettlAmount", "TotalAmount", "Year", "Month2", "Day2" };string[] testTablevalues = { "CustName", "GenderName", "LoanDate", "ContractName", "LoanAmount", "Periods", "MonthSupply", "RepaymentPeriod", "Periods2", "Month", "Day", "UnSettlAmount", "TotalAmount", "Year", "Month2", "Day2" };//循环所有的书签,并给书签赋值for (int oIndex = 0; oIndex < testTableremarks.Length; oIndex++){object obDD_Name = "";obDD_Name = testTableremarks[oIndex];//doc.Bookmarks.get_Item(ref obDD_Name).Range.Text = p_TestReportTable.Rows[0][testTablevalues[oIndex]].ToString();//此处Range也是WORD中很重要的一个对象,就是当前操作参数所在的区域
odf.get_Item(ref obDD_Name).Range.Text = testTablevalues[oIndex];}////附件,插入表格////这里简单生成样例数据表,工作中要以实际的数据集为准//System.Data.DataTable dt = new System.Data.DataTable();//dt.Columns.Add("name", typeof(string));//dt.Columns.Add("age", typeof(string));//DataRow dr = dt.NewRow();//dr["name"] = "姓名"; dr["age"] = "年龄";//dt.Rows.Add(dr);//dr = dt.NewRow();//dr["name"] = "张三"; dr["age"] = "20";//dt.Rows.Add(dr);//dr = dt.NewRow();//dr["name"] = "李四"; dr["age"] = "25";//dt.Rows.Add(dr);////附件一//object obAttachMent = "Attachment1";////创建Word表格,并指定标签//Microsoft.Office.Interop.Word.Table dtWord = doc.Tables.Add(odf.get_Item(ref obAttachMent).Range, dt.Rows.Count, dt.Columns.Count);//dtWord.Borders.InsideLineStyle = WdLineStyle.wdLineStyleDot;//dtWord.Borders.OutsideLineStyle = WdLineStyle.wdLineStyleDot;////循环往表格里赋值//for (int i = 1; i <= dt.Rows.Count; i++)//{//    for (int j = 1; j <= dt.Columns.Count; j++)//    {//        dtWord.Rows[i].Cells[j].Range.Text = dt.Rows[i - 1][j - 1].ToString();//    }//}//第四步 生成word,将当前的文档对象另存为指定的路径,然后关闭doc对象。关闭应用程序object filename = "d:\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".doc";//HttpContext.Current.Server.MapPath("f:\\") + "Testing_" + DateTime.Now.ToShortDateString() + ".doc"; //object Password = "P@55w0rd";////对Word文档进行加密保护,不允许编辑//if (Password != null)//{//    doc.Protect(WdProtectionType.wdAllowOnlyReading, ref objfalse, ref Password, ref miss, ref miss);//}
doc.SaveAs(ref filename, ref miss, ref miss, ref miss, ref miss, ref miss,ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;doc.Close(ref doNotSaveChanges, ref miss, ref miss);appWord.Application.Quit(ref miss, ref miss, ref miss);doc = null;appWord = null;//MessageBox.Show("生成成功!");//System.Diagnostics.Process.Start(filename.ToString());//打开文档
}catch (Exception ex){doc.Close(ref miss, ref miss, ref miss);appWord.Application.Quit(ref miss, ref miss, ref miss);doc = null;appWord = null;}return true;}}

View Code

使用方式      ---导出.docx出错

1)按书签导入值 书签设置见下方

ExportWord report = new ExportWord();
var path = System.Web.HttpContext.Current.Server.MapPath("/files/word/2.doc");
var savapath = System.Web.HttpContext.Current.Server.MapPath("/files/word/" + RandomStr.GetSerialNumber(4) + ".doc");
report.CreateNewDocument(path); //模板路径
report.InsertValue("name", "世界杯");//在书签“name”处插入值

View Code

2)导入表格 1
Table table2 = report.InsertTable("table2", 4, 4, 0); //在书签“table2”处插入2行3列行宽3)导入表格数据1
report.InsertCell(table2, 1, 1, "项目名称");//表名,行号,列号,值4)合并单元格1
report.MergeCell(table2, 1, 2, 1, 4); //表名,开始行号,开始列号,结束行号,结束列号5)设置字体大小1
report.SetFont_Table(table2, "宋体", 11);//宋体14磅6)文档保存1
report.SaveDocument(savapath);7)类中可修改的叮当1
table.Rows.Height = 40; //添加行时可 修改当前行的高度AddRow方法
1
//InsertTable方法修改回按书签的位置来添加表格 此方法不适用多个表格的导出
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public Table InsertTable(string bookmark, int rows, int columns, float width){object miss = System.Reflection.Missing.Value;object oStart = bookmark;Range range = wordDoc.Bookmarks.get_Item(ref oStart).Range;//表格插入位置Table newTable = wordDoc.Tables.Add(range, rows, columns, ref miss, ref miss);//设置表的格式newTable.Borders.Enable = 1; //允许有边框,默认没有边框(为0时报错,1为实线边框,2、3为虚线边框,以后的数字没试过)newTable.Borders.OutsideLineWidth = WdLineWidth.wdLineWidth050pt;//边框宽度if (width != 0){newTable.PreferredWidth = width;//表格宽度
           }newTable.AllowPageBreaks = false;return newTable;}wordApp.Selection.EndKey(WdUnits.wdStory);//焦点放到文档最后

View Code

5)注意点

1)表格导出时会嵌套表

原因 :表格导入完成后 焦点的位置默认会在表格里 在次插入会导致在表格内嵌套

解决:把焦点放到文档末尾 wordApp.Selection.EndKey(WdUnits.wdStory);

2)合并时会报所要求的的成员不存在

原因:这个错误的原因就是没有找到单元格,会有几种情况1)没有代码中定义的书签,2)表格前一项合并完 多列合成一列 后面再用之前的列值来合并。肯定找不到

解决:先输出对应的列与值,最后在处理合并。每次合并都记录,当前行的合并列数 如下

//处理合并
var pans = 0;//合并数
foreach (var o in lo)   //lo为一个list<other>
{report.MergeCell(table2, o.row, o.col1-pans, o.row, o.col2- pans);pans++;
}

View Code

3)书签的插入

word->插入->书签->输入书签名称->添加     (选项-高级-显示书签)

4)检索 COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问

原因:没有权限读取word.dll

解决:http://blog.csdn.net/ououou123456789/article/details/6102036

5)ApplicationClass() 不被识别

https://www.cnblogs.com/colder/p/5753159.html

https://www.cnblogs.com/itljf/p/5859445.html    

https://www.cnblogs.com/songjl/p/7469524.html

https://www.cnblogs.com/seejoy/p/6847570.html

https://blog.csdn.net/fraing/article/details/8989736  试卷

转载于:https://www.cnblogs.com/love201314/p/7612100.html

Aspose.Words导出图片 表格 Interop.Word相关推荐

  1. 导出带有表格的word文件时,换页自带表头,避免复杂的表格数行数计算

    选中要换页显示的表头,然后点布局下的重复标题行,保存即可,换页也是一个表格,插入数据的时候顺序插入即可,避免进行复杂的表格数,行号数计算

  2. Java POI导出(图片,文字,表格)word文档

    先给出官网链接,方便各位博友深入了解 http://deepoove.com/poi-tl/ 这里的教程,针对导出带有图片.文字.表格的Word文档 1.话不多说 先添加依赖 <dependen ...

  3. freemarker模板导出word循环图片表格详细教程

    前言:表哥之前已经过一篇freemarker模板导出带表格word详细教程  freemarker模板导出带表格word详细教程_Java大表哥的博客-CSDN博客,为什么现在又要写一篇呢. 因为我这 ...

  4. 【C#】C#使用Microsoft.Office.Interop.Word操作Word文档,向表格插入图片

    上篇:[C#]C#使用Microsoft.Office.Interop.Word操作Word文档,替换文本 Word模板: 代码: try {Application app = new Applica ...

  5. Java 导出word文档,遍历表格数据,导出图片

    引用:https://www.cnblogs.com/pxblog/p/13072711.html 1.引入maven依赖: <dependency><groupId>cn.a ...

  6. 【.NET】用Aspose.Words for .NET动态生成word文档中的数据表格

    1.概述 最近项目中有一个这样的需求:导出word 文档,要求这个文档的格式不是固定的,用户可以随便的调整,导出内容中的数据表格列是动态的,例如要求导出姓名和性别,你就要导出这两列的数据,而且这个文档 ...

  7. 关于.net Microsoft.Office.Interop.Word组建操作word的问题,如何控制word表格单元格内部段落的样式。...

    控制word表格单元格内部文字样式.我要将数据导出到word当中,对于word表格一个单元格中的一段文字,要设置不同的样式,比如第一行文字作为标题要居中,加粗,第二行为正常的正文. 代码如下 publ ...

  8. Java导出Word(导出图片,类,List)

    这里写自定义目录标题 一.Java导出一个List或者类 一.Java导出图片 一.Java导出一个List或者类 具体步骤如下: 首先需要创建一个模板 创建模板步骤: (1)创建想要导出的表格或者区 ...

  9. freemarker模板导出带表格word详细教程

    前言:另外一篇是手机端的word导出,需要兼容性,不然在安卓手机会乱码 freemarker模板导出word循环图片表格详细教程_Java大表哥的博客-CSDN博客  并且另存为模版格式不同数据绑定方 ...

最新文章

  1. 计算机网络分为两大阶段,【多选题】计算机网络的发展分为哪些阶段?() A. 远程终端联机阶段 B. 计算机网络阶段 C. 计算机网络互联阶段 D. 信息高速公路阶段...
  2. 余额宝技术架构读后感
  3. 在Windows上使用LaTeX
  4. Hibernate---进度1
  5. 背包(二维数组版和一维数组版)
  6. 【报告分享】面向数据流的产品迭代及业务闭环.pdf
  7. CvvImage.h和CvvImage.cpp
  8. 蓝桥训练系统 矩阵乘法
  9. 微信小程序云开发教程-云函数入门(1)-开发步骤
  10. 【POJ 3074】Sudoku【剪枝】
  11. MySQL 批量插入申请自增 ID
  12. 人员疏散模型(pso元胞自动机)网挑思路
  13. Android以太网架构源码
  14. es远程主机强迫关闭了一个现有的连接
  15. 小白 0-1 学习 app 开发,从配置到 hello world
  16. 无线笔记本怎么连接服务器打印机驱动,笔记本怎么连接无线打印机驱动程序
  17. 论如何写好一篇需求报告(或者说产品报告)
  18. 移动UI 设计有哪些色彩级别
  19. 智能化改造推动企业生产过程更为精准与高效
  20. 计算机启动显示不正确的分区表,每次开机提示invalid partition table怎么解决?

热门文章

  1. 兰戈 —— Rango
  2. C++用数组和链表分别实现Queue
  3. 二进制搜索树_二进制搜索树数据结构举例说明
  4. 问题 c: 插入排序_插入排序:它是什么,以及它如何工作
  5. cms基于nodejs_我如何使基于CMS的网站脱机工作
  6. 数据分析从头学_数据新闻学入门指南:让我们从头开始构建故事
  7. 2018湖湘杯海选复赛Writeup
  8. 参加软件测试培训前景怎么样
  9. 零基础学习Java培训有什么攻略
  10. linux下字符串处理工具二:awk( 二),awk脚本