当前位置: 首页 > 编程日记 > 正文

Aspose.Words导出图片 表格 Interop.Word

先定义一个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

相关文章:

[转帖]tar高级教程:增量备份、定时备份、网络备份

tar高级教程&#xff1a;增量备份、定时备份、网络备份 作者: lesca 分类: Tutorials, Ubuntu 发布时间: 2012-03-01 11:42 ė浏览 27,065 次 61条评论一、概述 备份与恢复对于系统维护而言是至关重要的事情。不合理的备份与还原会让你的数据面临丢失的风险。许多用户都在丢失重…

C# 异步读取数据库里面的数据与绑定UI的解决办法

异步读取数据库,在数据绑定的时候会出现点问题,就是窗体界面会无法关闭,要结束任务才能结束进程。例如下面代码 首先按习惯的方法&#xff0c;设定线程更新UI a2.CheckForIllegalCrossThreadCalls false; //a2为窗体名称 下面的代码就是从数据库里取得数据并绑定 private vo…

类、抽象类、接口之间的区别

目录 1、类与抽象类的异同之处 &#xff08;1&#xff09;类和抽象类的区别 &#xff08;2&#xff09;类和抽象类的相同之处 2、接口与类的异同之处 &#xff08;1&#xff09;接口与类相似点 &#xff08;2&#xff09;接口与类的区别 &#xff08;3&#xff09;接口…

(ASA) Cisco Web ××× 配置详解 [三部曲之一]

(ASA) Cisco Web 配置详解 [三部曲之一] 注意&#xff1a;本文仅对Web特性和配置作介绍&#xff0c;不包含SSL 配置&#xff0c;SSL 配置将在本版的后续文章中进行介绍。 首先&#xff0c;先来谈一谈ASA7.X系统中的默认隧道组和组策略。ASA/PIX 7.x系统默认在show run时不显示…

IDEA和Eclipse设置文件编码格式

1、IDEA设置已有文件的编码格式 在页面右下角可以看到文件的编码方式&#xff0c;如果编码方式的图标为灰色&#xff0c;则无法修改编码格式&#xff1b;如果其颜色不是灰色且其右侧有上下方向的三角形形状&#xff0c;点击它&#xff0c;可以修改编码方式。 注意&#xff1a;该…

关于运行ssm,web请求出现HTTP415错误

HTTP415错误&#xff1a;如果controller中用到了json传值&#xff0c;那么就必须加入 <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <jackson.version>2.…

堆和栈浅析【转】

引用&#xff1a; 一、预备知识—程序的内存分配一个由c/C编译的程序占用的内存分为以下几个部分1、栈区&#xff08;stack&#xff09;— 由编译器自动分配释放 &#xff0c;存放函数的参数值&#xff0c;局部变量的值等。其操作方式类似于数据结构中的栈。2、堆区&#xff…

JS-只能输入中文和英文

<span style"font-family:KaiTi_GB2312;">转自&#xff1a;<a target_blank href"http://www.cnblogs.com/liupeizhi/articles/2487472.html">http://www.cnblogs.com/liupeizhi/articles/2487472.html</a></span> </pre>&l…

SQL Server中读取XML文件的简单做法

SQL Server 2000使得以XML导出数据变得更加简单&#xff0c;但在SQL Server 2000中导入XML数据并对其进行处理则有些麻烦。本文介绍在SQL Server中读取XML文件的简单做法。SQL Server 2000使得以XML导出数据变得更加简单&#xff0c;但在SQL Server 2000中导入XML数据并对其进行…

Calling Oracle stored procedures from Microsoft.NET

摘自&#xff1a;http://www.c-sharpcorner.com/UploadFile/john_charles/CallingOraclestoredproceduresfromMicrosoftdotNET06222007142805PM/CallingOraclestoredproceduresfromMicrosoftdotNET.aspxIntroduction This article is intended to illustrate how to illustrate…

Https的底层原理

Http协议&#xff1a; 转载于:https://www.cnblogs.com/auldlangsynezh/p/10469587.html

【Linux笔记(002) 】-- centos7 文档操作基本命令

索引&#xff1a; 目录索引 一、cd -- ChangeDirectory a) 切换到 /DemoLM/ 文件夹 b) 回到用户 Home 根目录&#xff1a;是哪个账户登录的就会进入哪个用户的根目录 二、pwd -- PrintWorkingDirectory a) 查看当前工作目录 三、mkdir -- MakeDirectory a) 创建一个 /test/ 目录…

JDBC操作数据库实例

返回目录&#xff1a;《学生信息管理系统&#xff08;JavaJSP&#xff09;》 这里以JDBC操作MySQL数据库为例。 假设有一个名为test的数据库&#xff0c;里面有一张学生表&#xff0c;表名称为student&#xff0c;表结构如下&#xff1a; student表结构表中数据如下&#xff1…

面向JavaScript开发人员的Adobe AIR与Dreamweaver

入门教程&#xff0c;非常详细&#xff0c;CS4里面应该可以省略前面几步直接开发了。 Adobe AIR对于HTML/JavaScript应用程序与桌面的集成有着出色的支持&#xff0c;但除了所有附加功能之外&#xff0c;还需要一些其他工具和技术。这篇文章探讨了使用HTML/JavaScript的Web开发…

在数据显示页面增加按姓名查询功能

在上一章内容《将数据库中表格信息输出到页面上》的基础上&#xff0c;增加按姓名查询功能。 问&#xff1a;怎么在显示学生信息的页面增加按照姓名查询的功能&#xff1f; 答&#xff1a;在显示学生信息的页面&#xff0c;使用<form>标签为用户创建表单&#xff0c;表单…

Spring AOP的一些概念

切面&#xff08;Aspect&#xff09;&#xff1a; 一个关注点的模块化&#xff0c;这个关注点可能会横切多个对象。事务管理是J2EE应用中一个关于横切关注点的很好的例子。 在Spring AOP中&#xff0c;切面可以使用通用类&#xff08;基于模式的风格&#xff09; 或者在普通类中…

有关于Matlab的regionprops函数的PixelIdxList和PixelList的一点解释

上一篇文章&#xff08;点击这里&#xff09;的最后一点说到了regionprops的相关参数的意思&#xff0c;但是总感觉不够明确 现在重新对PixelIdxList和PixelList的内容经过实验之后得到了点启发 1.首先用excel建立了一个如下的表格&#xff0c;然后用mat保存为mat的方式进行加载…

windows 系统无法启动windows event log 服务

windows 系统无法启动windows event log 服务 关键词&#xff1a;无法启动系统事件日志 尝试解决步骤 【1】权限&#xff1a;把如图中logsfile文件等都给local service 【2】把C:\Windows\System32\winevt\Logs下面的文件全部移走到其他文件夹&#xff0c;再启动服务试试看 【…

移动互联网漫谈(3)

1.1WIFI WIFI是无线局域网的一种&#xff0c;全称Wireless Fidelity&#xff0c;又称802.11b标准&#xff0c;它的最大优点就是传输速度较高&#xff0c;可以达到11Mbps&#xff0c;另外它的有效距离也很长&#xff0c;同时也与已有的各种802.11 DSSS设备兼容。今夏最流行的笔…

实现对学生表的删除操作

在上一章内容《数据显示页面》的基础上&#xff0c;增加删除超链接&#xff0c;实现删除功能&#xff1b; 修改内容&#xff1a; 在数据显示页面的表格中&#xff0c;增加一列&#xff0c;列名为“删除”&#xff0c;用来显示删除超链接&#xff1b;为表格的行标签&#xff08…

FRAME与IFRAME

FRAME与IFRAME框架概念 &#xff1a; 所谓框架便是网页画面分成几个框窗&#xff0c;同时取得多个 URL。只需要转载于:https://www.cnblogs.com/vibratea/archive/2009/07/24/1530098.html

react实现全选、取消全选和个别选择

react里面实现全选和取消全选&#xff0c;个别选择等操作&#xff0c;效果如下 代码&#xff1a; import React, {Component} from react export default class Demo extends React.Component{constructor(props,context){super(props,context);this.state {checklist:[{name:…

PAT1036:Boys vs Girls

1036. Boys vs Girls (25) 时间限制400 ms内存限制65536 kB代码长度限制16000 B判题程序Standard作者CHEN, YueThis time you are asked to tell the difference between the lowest grade of all the male students and the highest grade of all the female students. Input …

NERO7光雕功能

找到NERO 7 PREMIUM的这个版本&#xff1a;Nero-7.10.1.0_chs_trial.exe百度中搜这个文件就找到了&#xff0c;用下面的序列号&#xff1a;1C80-0000-19E5-MA2X-4004-9268-7320&#xff0c;再装上最新版的官方光雕程序&#xff08;集成了加深标签的插件&#xff09;&#xff1a…

hive函数 get_json_object的使用

hive提供了json的解析函数&#xff1a;get_json_object 使用方法 对于jsonArray&#xff08;json数组&#xff09;&#xff0c;如person表的xjson字段有数据&#xff1a; [{"name":"王二狗","sex":"男","age":"25"…

实现对学生信息的增加操作

上一篇博客&#xff1a;《实现对学生表的删除操作》返回目录&#xff1a;《学生信息管理系统&#xff08;JavaJSP&#xff09;》本篇博客将介绍如何实现学生表中学生信息的增加操作。 1、在test1模块的web目录下&#xff0c;新建一个stuAddForm.jsp文件&#xff08;文件内容如…

【BZOJ 3879】SvT

【链接】h在这里写链接 【题意】 给你一个长度为n的字符串以及m个询问。 每个询问询问你所给的一些后缀,所有任意两个后缀之间的lcp的总和; n<5*10^5 ∑t<3*10^6【题解】 按照这些后缀的rank值升序排 ->利用Sa数组 即输入一个x,x--; sort(a1,…

快速计算表达式树

前言 .NET 3.5中新增的表达式树&#xff08;Expression Tree&#xff09;特性&#xff0c;第一次在.NET平台中引入了“逻辑即数据”的概念。也就是说&#xff0c;我们可以在代码里使用高级语言的形式编写一段逻辑&#xff0c;但是这段逻辑最终会被保存为数据。正因为如此&#…

随手拈来尽是折劲额事体

昨天中午&#xff0c;justina同学请我去港丽吃饭&#xff0c;世界顿时美好了&#xff01; 猛地发现&#xff0c;港丽的酸菜鱼竟然非常好吃&#xff0c;除了价钱贵&#xff0c;基本没有缺点了。 吃饭的时候&#xff0c;看到两件有劲的事情&#xff0c;一件比一件更折劲&#xff…

06 面向对象之:反射,双下方法

一、反射 反射的概念是由Smith在1982年首次提出的&#xff0c;主要是指程序可以访问、检测和修改它本身状态或行为的一种能力&#xff08;自省&#xff09;。这一概念的提出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象…