zoukankan      html  css  js  c++  java
  • Aspose.Words导出图片 表格 Interop.Word

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

    文本和段落

                    // Specify font formatting
                    Aspose.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 formatting
                    ParagraphFormat paragraphFormat = builder.ParagraphFormat;
                    paragraphFormat.FirstLineIndent = 8;
                    paragraphFormat.Alignment = ParagraphAlignment.Justify;
                    paragraphFormat.KeepTogether= true;
    
                    builder.Writeln("A whole paragraph.");  //插入一段文本(需要加格式的ParagraphFormat)
    View Code
                        //Specify paragraph formatting
                        ParagraphFormat 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();
                //    }
                //}
    
                #endregion
    
                doc.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);
                    //删除HTML
                    Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
                    Htmlstring = Regex.Replace(Htmlstring, @"([
    ])[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("
    ", "");
                    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 = "
    ";
            }
    
            //杀掉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	z103.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  试卷

  • 相关阅读:
    springIOC 原理
    jeesite异步分页
    yum
    乐观锁原理
    equlas(),hashcode(),hashset,hashmap
    链接收藏
    java单词
    jeesite优化
    SailingEase .NET Resources Tool (.NET 多语言资源编辑器)转
    C#基本语法
  • 原文地址:https://www.cnblogs.com/love201314/p/7612100.html
Copyright © 2011-2022 走看看