/// <summary>
        /// 创建word文档中的段落对象和设置段落文本的基本样式(字体大小,字体,字体颜色,字体对齐位置)
        /// </summary>
        /// <param name="document">document文档对象</param>
        /// <param name="fillContent">段落第一个文本对象填充的内容</param>
        /// <param name="isBold">是否加粗</param>
        /// <param name="fontSize">字体大小</param>
        /// <param name="fontFamily">字体</param>
        /// <param name="paragraphAlign">段落排列(左对齐,居中,右对齐)</param>
        /// <param name="isStatement">是否在同一段落创建第二个文本对象(解决同一段落里面需要填充两个或者多个文本值的情况,多个文本需要自己拓展,现在最多支持两个)</param>
        /// <param name="secondFillContent">第二次声明的文本对象填充的内容,样式与第一次的一致</param>
        /// <returns></returns>
        private static XWPFParagraph ParagraphInstanceSetting(XWPFDocument document, string fillContent, bool isBold, int fontSize, string fontFamily, ParagraphAlignment paragraphAlign, bool isStatement = false, string secondFillContent = "")
        {
            XWPFParagraph paragraph = document.CreateParagraph();  //创建段落对象

            paragraph.Alignment = paragraphAlign;                  //文字显示位置,段落排列(左对齐,居中,右对齐)

            XWPFRun xwpfRun = paragraph.CreateRun();               //创建段落文本对象

            xwpfRun.IsBold = isBold;                               //文字加粗
            xwpfRun.SetText(fillContent);                          //填充内容
            xwpfRun.FontSize = fontSize;                           //设置文字大小
            xwpfRun.SetFontFamily(fontFamily, FontCharRange.None); //设置标题样式如:(微软雅黑,隶书,楷体)根据自己的需求而定

            if (isStatement)
            {
                XWPFRun secondxwpfRun = paragraph.CreateRun();               //创建段落文本对象
                secondxwpfRun.IsBold = isBold;                               //文字加粗
                secondxwpfRun.SetText(secondFillContent);                    //填充内容
                secondxwpfRun.FontSize = fontSize;                           //设置文字大小
                secondxwpfRun.SetFontFamily(fontFamily, FontCharRange.None); //设置标题样式如:(微软雅黑,隶书,楷体)根据自己的需求而定
            }


            return(paragraph);
        }
Exemple #2
0
        /// <summary>
        /// 设置数据文档的表
        /// </summary>
        /// <param name="document">文档</param>
        /// <param name="table">当前表</param>
        /// <param name="no">当前表编号,从1开始</param>
        public static void SetTableWord(XWPFDocument document, TableMeta table, Int32 no)
        {
            //表名
            XWPFParagraph p = document.CreateParagraph();

            p.Alignment = ParagraphAlignment.LEFT;
            XWPFRun r = p.CreateRun();

            r.SetText($"{no}.{table.TableName}");
            r.FontSize = 14;
            r.IsBold   = true;

            if (!string.IsNullOrEmpty(table.Comment))
            {
                //表注释
                p           = document.CreateParagraph();
                p.Alignment = ParagraphAlignment.LEFT;
                r           = p.CreateRun();
                r.SetText(table.Comment);
                r.FontSize = 14;
                r.IsBold   = true;
            }


            //表格
            XWPFTable grid = document.CreateTable(table.Columns.Count + 1, 5);



            grid.Width = 2500;
            grid.SetColumnWidth(0, 256 * 2);
            grid.SetColumnWidth(1, 256 * 2);
            grid.SetColumnWidth(2, 256 * 1);
            grid.SetColumnWidth(3, 256 * 1);
            grid.SetColumnWidth(4, 256 * 4);



            //设置表头
            XWPFTableRow row = grid.GetRow(0);

            row.GetCell(0).SetParagraph(SetCellText(document, grid, "字段名"));
            row.GetCell(1).SetParagraph(SetCellText(document, grid, "类型"));
            row.GetCell(2).SetParagraph(SetCellText(document, grid, "是否主键"));
            row.GetCell(3).SetParagraph(SetCellText(document, grid, "可为空"));
            row.GetCell(4).SetParagraph(SetCellText(document, grid, "说明"));

            for (int i = 0; i < table.Columns.Count; i++)
            {
                ColumnMeta col = table.Columns[i];
                row = grid.GetRow(i + 1);
                row.GetCell(0).SetParagraph(SetCellText(document, grid, col.ColumnName));
                row.GetCell(1).SetParagraph(SetCellText(document, grid, col.FieldTypeName));
                row.GetCell(2).SetParagraph(SetCellText(document, grid, col.IsKey ? "是" : "否"));
                row.GetCell(3).SetParagraph(SetCellText(document, grid, col.AllowDBNull ? "是" : "否"));
                row.GetCell(4).SetParagraph(SetCellText(document, grid, string.IsNullOrEmpty(col.Comment)?string.Empty:col.Comment));
            }
        }
Exemple #3
0
        private static void DoAddPicture(XWPFParagraph paragraph, List <AddPictureOptions> listAddPictureOptions)
        {
            XWPFRun         textRun, imgRun, placeHolderRun;
            IList <XWPFRun> listRun = paragraph.Runs;

            for (int i = 0; i < listRun.Count; i++)
            {
                placeHolderRun = paragraph.Runs[i];

                for (int j = 0; j < listAddPictureOptions.Count; j++)
                {
                    var addPictureOptions = listAddPictureOptions[j];
                    if (addPictureOptions.PlaceHolder.ToString() == placeHolderRun.Text)
                    {
                        if (j == 0)
                        {
                            paragraph.RemoveRun(i);
                        }

                        textRun = paragraph.CreateRun();

                        string newText = addPictureOptions.PictureName + Environment.NewLine;
                        if (j > 0)
                        {
                            newText = Environment.NewLine + "    " + newText;
                        }

                        //textRun.SetText(newText);
                        textRun.SetText(string.Empty);

                        CopyRunStyle(placeHolderRun, textRun);

                        imgRun = paragraph.CreateRun();

                        if (File.Exists(addPictureOptions.LocalPictureUrl))
                        {
                            using (FileStream fs = File.OpenRead(addPictureOptions.LocalPictureUrl))
                            {
                                imgRun.AddPicture(
                                    fs,
                                    (int)GetPictureTypeFromUrl(addPictureOptions.LocalPictureUrl),
                                    addPictureOptions.ImageType.ToString() + Path.GetExtension(addPictureOptions.LocalPictureUrl),
                                    5000000,
                                    3000000);
                                CT_Inline inline = imgRun.GetCTR().GetDrawingList()[0].inline[0];
                                inline.docPr.id = addPictureOptions.PicId; //id必须从1开始
                            }
                        }
                    }
                }
            }
        }
Exemple #4
0
        public string Test()
        {
            string       unique_file_name = Guid.NewGuid().ToString() + ".docx";
            string       file_path        = Path.Combine("wwwroot", "awards", unique_file_name);
            XWPFDocument doc = new XWPFDocument();
            // 添加段落
            XWPFParagraph gp = doc.CreateParagraph();

            gp.Alignment = ParagraphAlignment.CENTER;//水平居中
            XWPFRun gr = gp.CreateRun();

            gr.GetCTR().AddNewRPr().AddNewRFonts().ascii    = "黑体";
            gr.GetCTR().AddNewRPr().AddNewRFonts().eastAsia = "黑体";
            //gr.GetCTR().AddNewRPr().AddNewRFonts().hint = ST_Hint.eastAsia;
            gr.GetCTR().AddNewRPr().AddNewSz().val    = (ulong)44; //2号字体
            gr.GetCTR().AddNewRPr().AddNewSzCs().val  = (ulong)44;
            gr.GetCTR().AddNewRPr().AddNewB().val     = true;      //加粗
            gr.GetCTR().AddNewRPr().AddNewColor().val = "red";     //字体颜色
            gr.SetText("NPOI创建Word2007Docx");

            FileStream fs = new FileStream(file_path, FileMode.OpenOrCreate, FileAccess.Write);

            doc.Write(fs);
            Console.WriteLine("生成word成功");

            return("ok admin/test");
        }
Exemple #5
0
        public byte[] CreateWord(Dictionary <string, string> paragraphs)
        {
            if (paragraphs == null)
            {
                throw new ArgumentNullException(nameof(paragraphs));
            }

            var doc = new XWPFDocument();

            try
            {
                //创建段落对象
                foreach (var key in paragraphs.Keys)
                {
                    XWPFParagraph paragraph = doc.CreateParagraph();
                    XWPFRun       run       = paragraph.CreateRun();
                    run.IsBold = true;
                    run.SetText(ConvertHelper.GetString(key));
                    run.SetText(ConvertHelper.GetString(paragraphs[key]));
                }

                using (var stream = new MemoryStream())
                {
                    doc.Write(stream);
                    var bs = stream.ToArray();
                    return(bs);
                }
            }
            finally
            {
                doc.Close();
            }
        }
Exemple #6
0
        public static byte[] CreateWord(Dictionary <string, string> paragraphs)
        {
            var doc = new XWPFDocument();

            try
            {            //创建段落对象
                paragraphs = paragraphs ?? new Dictionary <string, string>()
                {
                };
                paragraphs.Keys.ToList().ForEach(key =>
                {
                    XWPFParagraph paragraph = doc.CreateParagraph();
                    XWPFRun run             = paragraph.CreateRun();
                    run.IsBold = true;
                    run.SetText(ConvertHelper.GetString(key));
                    run.SetText(ConvertHelper.GetString(paragraphs[key]));
                });
                using (var stream = new MemoryStream())
                {
                    doc.Write(stream);
                    var bs = stream.ToArray();
                    return(bs);
                }
            }
            finally
            {
                doc.Close();
            }
        }
Exemple #7
0
        public void TestSetParagraphStyle()
        {
            //new clean instance of paragraph
            XWPFDocument  doc = XWPFTestDataSamples.OpenSampleDocument("heading123.docx");
            XWPFParagraph p   = doc.CreateParagraph();
            XWPFRun       run = p.CreateRun();

            run.SetText("Heading 1");

            CT_SdtBlock block = doc.Document.body.AddNewSdt();

            Assert.IsNull(p.Style);
            p.Style = HEADING1;
            Assert.AreEqual(HEADING1, p.GetCTP().pPr.pStyle.val);

            doc.CreateTOC();

            /*
             * // TODO - finish this test
             * if (false) {
             *  CTStyles styles = doc.Style;
             *  CTStyle style = styles.AddNewStyle();
             *  style.Type=(STStyleType.PARAGRAPH);
             *  style.StyleId=("Heading1");
             * }
             *
             * if (false) {
             *  File file = TempFile.CreateTempFile("testHeaders", ".docx");
             *  OutputStream out1 = new FileOutputStream(file);
             *  doc.Write(out1);
             *  out1.Close();
             * }
             */
        }
Exemple #8
0
        // word 添加文字
        public static void AddParagrath(XWPFDocument doc, string content)
        {
            XWPFParagraph para = doc.CreateParagraph();
            XWPFRun       run  = para.CreateRun();

            run.SetText(content);
        }
Exemple #9
0
        static void Main(string[] args)
        {
            // Create a new document from scratch
            XWPFDocument doc   = new XWPFDocument();
            XWPFTable    table = doc.CreateTable(3, 3);

            table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE");

            XWPFTableCell c1 = table.GetRow(0).GetCell(0);
            XWPFParagraph p1 = c1.AddParagraph();   //don't use doc.CreateParagraph
            XWPFRun       r1 = p1.CreateRun();

            r1.SetText("This is test table contents");
            r1.IsBold = true;

            r1.FontFamily = "Courier";
            r1.SetUnderline(UnderlinePatterns.DotDotDash);
            r1.SetTextPosition(100);
            c1.SetColor("FF0000");


            table.GetRow(2).GetCell(2).SetText("only text");

            FileStream out1 = new FileStream("data/Format Table in Document.docx", FileMode.Create);

            doc.Write(out1);
            out1.Close();
        }
Exemple #10
0
        static void Main(string[] args)
        {
            XWPFDocument  doc  = new XWPFDocument();
            XWPFParagraph para = doc.CreateParagraph();
            XWPFRun       r0   = para.CreateRun();

            r0.SetText("Title1");
            para.BorderTop           = Borders.Thick;
            para.FillBackgroundColor = "EEEEEE";
            para.FillPattern         = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe;

            XWPFTable table = doc.CreateTable(3, 3);

            table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE");

            XWPFTableCell c1 = table.GetRow(0).GetCell(0);
            XWPFParagraph p1 = c1.AddParagraph();   // Use this instead of doc.CreateParagraph.
            XWPFRun       r1 = p1.CreateRun();

            r1.SetText("The quick brown fox");
            r1.IsBold = true;

            r1.FontFamily = "Courier";
            r1.SetUnderline(UnderlinePatterns.DotDotDash);
            r1.TextPosition = 100;
            c1.SetColor("FF0000");

            table.GetRow(2).GetCell(2).SetText("only text");

            FileStream out1 = new FileStream("SimpleTableNPOI.docx", FileMode.Create);

            doc.Write(out1);
            out1.Close();
        }
Exemple #11
0
        public static XWPFParagraph Set(this XWPFParagraph p, Paragraph paragraph)
        {
            p.Alignment = GetNPOIAlignment(paragraph.Alignment);
            p.CreateRun().Set(paragraph.Run);

            return(p);
        }
Exemple #12
0
        public void SetText(string text)
        {
            CT_P          ctP = (ctTc.SizeOfPArray() == 0) ? ctTc.AddNewP() : ctTc.GetPArray(0);
            XWPFParagraph par = new XWPFParagraph(ctP, this);

            par.CreateRun().AppendText(text);
        }
Exemple #13
0
        public byte[] CreateWordDocument()
        {
            XWPFDocument doc = new XWPFDocument();

            XWPFParagraph p1 = doc.CreateParagraph();


            XWPFRun r1 = p1.CreateRun();

            r1.SetText("The quick brown fox");
            r1.IsBold     = true;
            r1.FontFamily = "Arial";
            r1.SetUnderline(UnderlinePatterns.DotDotDash);
            r1.SetTextPosition(100);

            MemoryStream memoryStream = new MemoryStream();

            StreamWriter wr = new StreamWriter(memoryStream);


            //保存文档
            doc.Write(memoryStream);

            return(memoryStream.ToArray());
        }
        public void createWord(string strFileName, string body)
        {
            XWPFDocument doc = new XWPFDocument();

            doc.CreateParagraph();
            XWPFParagraph p1        = doc.CreateParagraph();
            XWPFRun       rUserHead = p1.CreateRun();

            rUserHead.SetText(body);
            rUserHead.SetColor("4F6B72");

            rUserHead.FontSize   = 15;
            rUserHead.IsBold     = true;
            rUserHead.FontFamily = "宋体";
            //r1.SetUnderline(UnderlinePatterns.DotDotDash);
            //位置
            rUserHead.SetTextPosition(20);

            //增加换行

            rUserHead.AddCarriageReturn();

            FileStream sw = File.OpenWrite(strFileName);

            doc.Write(sw);
            sw.Close();
            MessageBox.Show("下载完成!" + strFileName, "下载word");
        }
        private void RenderCrossReferences(StyleConfig config)
        {
            if (CrossRefMarkers.Count > 0)
            {
                XWPFParagraph renderCrossRefStart = newDoc.CreateParagraph();
                renderCrossRefStart.BorderTop = Borders.Single;

                StyleConfig markerStyle = (StyleConfig)config.Clone();
                markerStyle.fontSize = 12;

                foreach (KeyValuePair <string, Marker> crossRefKVP in CrossRefMarkers)
                {
                    XWPFParagraph renderCrossRef = newDoc.CreateParagraph();
                    renderCrossRef.SetBidi(configDocx.rightToLeft);
                    XWPFRun crossRefMarker = renderCrossRef.CreateRun(markerStyle);
                    setRTL(crossRefMarker);
                    crossRefMarker.SetText(crossRefKVP.Key);
                    crossRefMarker.Subscript = VerticalAlign.SUPERSCRIPT;

                    foreach (Marker input in crossRefKVP.Value.Contents)
                    {
                        RenderMarker(input, markerStyle, renderCrossRef);
                    }
                }
                CrossRefMarkers.Clear();
            }
        }
Exemple #16
0
        static void Main(string[] args)
        {
            XWPFDocument doc = new XWPFDocument();

            XWPFTable table = doc.CreateTable(3, 3);

            table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE");


            XWPFParagraph p1 = doc.CreateParagraph();

            XWPFRun r1 = p1.CreateRun();

            r1.SetBold(true);
            r1.SetText("The quick brown fox");
            r1.SetBold(true);
            r1.SetFontFamily("Courier");
            r1.SetUnderline(UnderlinePatterns.DotDotDash);
            r1.SetTextPosition(100);

            table.GetRow(0).GetCell(0).SetParagraph(p1);


            table.GetRow(2).GetCell(2).SetText("only text");

            FileStream out1 = new FileStream("simpleTable.docx", FileMode.Create);

            doc.Write(out1);
            out1.Close();
        }
Exemple #17
0
        private void ReplaceKey(XWPFParagraph para, Dictionary <string, object> model)
        {
            string text    = para.ParagraphText;
            var    runs    = para.Runs;
            int    length  = runs.Count();
            string styleid = para.Style;

            text = String.Join("", runs.Select(x => x.Text));
            foreach (var p in model)
            {
                //$$与模板中$$对应,也可以改成其它符号,比如{$name},务必做到唯一
                if (text.Contains("${" + p.Key + "}"))
                {
                    if (p.Value.GetType().Name.Equals("String"))
                    {
                        text = text.Replace("${" + p.Key + "}", p.Value.ToString());
                    }
                    else
                    {
                        text = text.Replace("${" + p.Key + "}", "");
                        var        gr    = para.CreateRun();
                        FileStream fs    = (FileStream)p.Value;
                        var        picID = para.Document.AddPictureData(fs, (int)PictureType.JPEG);
                        CreatePicture(para, picID, 150, 200);
                    }
                }
            }
            for (int j = (length - 1); j >= 0; j--)
            {
                para.RemoveRun(j);
            }
            //直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
            //所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
            para.InsertNewRun(0).SetText(text, 0);
        }
Exemple #18
0
        private static void WriteByReadTemplate()
        {
            using (var dotStream = new FileStream("read.docx", FileMode.Open, FileAccess.Read))
            {
                XWPFDocument template = new XWPFDocument(dotStream);

                using (var fileStream = new FileStream("test.docx", FileMode.Create, FileAccess.Write))
                {
                    XWPFDocument document  = new XWPFDocument();
                    XWPFStyles   newStyles = document.CreateStyles();
                    newStyles.SetStyles(template.GetCTStyle());

                    XWPFParagraph paragraph = document.CreateParagraph();
                    paragraph.Style = "a3";
                    XWPFRun xwpfRun = paragraph.CreateRun();
                    xwpfRun.SetText("标题内容");

                    XWPFParagraph paragraph1 = document.CreateParagraph();
                    paragraph1.Style = "1";
                    XWPFRun xwpfRun1 = paragraph1.CreateRun();
                    xwpfRun1.SetText("标题1内容");

                    XWPFParagraph paragraph2 = document.CreateParagraph();
                    paragraph2.Style = "2";
                    XWPFRun xwpfRun2 = paragraph2.CreateRun();
                    xwpfRun2.SetText("标题2内容");

                    document.Write(fileStream);

                    document.Close();
                }
                template.Close();
            }
        }
Exemple #19
0
 /// <summary>
 /// word文档插入图片
 /// </summary>
 private static void word_insert_picture(XWPFDocument m_Docx, string prjName, string photoPathName)
 {
     System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(".\\Picture\\" + prjName + "\\" + photoPathName);
     if (dir.Exists == false)
     {
         Log.Err(TAG, "路径不存在");
         return;
     }
     System.IO.FileInfo[] files = dir.GetFiles(); // 获取所有文件信息。。
     foreach (System.IO.FileInfo file in files)
     {
         FileStream gfs = new FileStream(".\\Picture\\" + prjName + "\\" + photoPathName + "\\" + file.Name,
                                         FileMode.Open, FileAccess.Read);
         XWPFParagraph gp = m_Docx.CreateParagraph(); //创建XWPFParagraph
         gp.SetAlignment(ParagraphAlignment.CENTER);
         XWPFRun gr = gp.CreateRun();
         //添加图片(注意设置图片的大小) 默认最小的一边为1000000
         System.Drawing.Image image = System.Drawing.Image.FromFile(".\\Picture\\" + prjName + "\\" + photoPathName + "\\" + file.Name);
         int height, width;
         if (image.Height > image.Width)
         {
             height = 3000000;
             width  = 2000000;
         }
         else
         {
             height = 2000000;
             width  = 3000000;
         }
         gr.AddPicture(gfs, (int)NPOI.XWPF.UserModel.PictureType.JPEG, file.Name, width, height);
         gfs.Close();
     }
 }
        public void TestIntegration()
        {
            XWPFDocument doc = new XWPFDocument();

            XWPFParagraph p1 = doc.CreateParagraph();

            XWPFRun r1 = p1.CreateRun();

            r1.SetText("Lorem ipsum dolor sit amet.");
            doc.EnforceCommentsProtection();

            FileInfo tempFile = TempFile.CreateTempFile("documentProtectionFile", ".docx");

            if (File.Exists(tempFile.FullName))
            {
                File.Delete(tempFile.FullName);
            }
            Stream out1 = new FileStream(tempFile.FullName, FileMode.CreateNew);

            doc.Write(out1);
            out1.Close();

            FileStream   inputStream = new FileStream(tempFile.FullName, FileMode.Open);
            XWPFDocument document    = new XWPFDocument(inputStream);

            inputStream.Close();

            Assert.IsTrue(document.IsEnforcedCommentsProtection());
        }
        /// <summary>
        /// 将表生成字段
        /// </summary>
        /// <param name="fileName">生成文件的名称</param>
        /// <param name="sql">获取数据库所有表 SELECT name FROM tmc..sysobjects Where xtype='U' ORDER BY name </param>
        /// <param name="WordFieldName"> Word中列的名称</param>
        public override void CreateTablesToWord(string fileName, string[] wordFieldName)
        {
            using (var fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
            {
                var           m_Docx = CreateXWPFDocument(fileName);
                XWPFParagraph p0     = m_Docx.CreateParagraph();
                XWPFRun       r0     = p0.CreateRun();
                r0.SetText("DOCX表");

                //获取数据源
                var tables = con.Query <TablesName>(_getTablesSql).ToList();

                for (int i = 0; i < tables.Count; i++)
                {
                    //获取 数据源
                    var FieldNames = GetTableFileds(tables[i].Tables_in_Tmc);

                    XWPFTable table = m_Docx.CreateTable(2, 4);//创建一行四列表

                    //每一行的中文名称 比如 字段 数据类型 可为空 描述
                    for (int icol = 0; icol < 4; icol++)
                    {
                        table.GetRow(1).GetCell(icol).SetText(wordFieldName[icol]);
                        table.GetRow(1).GetCell(icol).SetColor("#BABABA");
                    }

                    //  数据库中的字段名称,类型备注信息
                    for (int j = 1; j < FieldNames.Count; j++)
                    {
                        XWPFTableRow m_Row = table.CreateRow();
                        m_Row.GetCell(0).SetText(FieldNames[j].COLUMN_NAME);
                        m_Row.GetCell(1).SetText(FieldNames[j].DotNet_DATA_TYPE);
                        m_Row.GetCell(2).SetText(FieldNames[j].IsNullAble);
                        m_Row.GetCell(3).SetText(FieldNames[j].COLUMN_COMMENT);
                    }

                    //标注表名,如果放在放在上面,只能生成一列,这样88行会报错
                    table.GetRow(0).MergeCells(0, 3);
                    table.GetRow(0).GetCell(0).SetText(tables[i].Tables_in_Tmc);
                    table.GetRow(0).GetCell(0).SetColor("#98FB98");
                    table.GetRow(0).GetCTRow().AddNewTrPr().AddNewTrHeight().val = (ulong)500;

                    //创建一个空白行分隔每个表,并添加每一行标题
                    CT_P newLine = m_Docx.Document.body.AddNewP();
                    newLine.AddNewPPr().AddNewJc().val = ST_Jc.center;           //段落水平居中
                    XWPFParagraph gp       = new XWPFParagraph(newLine, m_Docx); //创建XWPFParagraph
                    XWPFRun       runTitle = gp.CreateRun();
                    runTitle.IsBold = true;
                    runTitle.SetText(i.ToString() + "." + tables[i].Tables_in_Tmc);
                    runTitle.FontSize = 16;
                    runTitle.SetFontFamily("宋体", FontCharRange.None);//设置雅黑字体
                }

                MemoryStream ms = new MemoryStream();
                m_Docx.Write(ms);
                ms.Flush();
                SaveToFile(ms, "d:\\Tmc数据库表字段说明.docx");
            }
        }
Exemple #22
0
        /// <summary>
        /// 创建普通文本段
        /// </summary>
        /// <param name="doc"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public static XWPFRun CreateParagraph(this XWPFDocument doc, string text)
        {
            XWPFParagraph paragraph = doc.CreateParagraph();
            XWPFRun       run       = paragraph.CreateRun();

            run.SetText(text);
            return(run);
        }
Exemple #23
0
        private static void DoAddTable(XWPFDocument doc, XWPFTableCell cell, XWPFParagraph paragraph, AddTableOptions TableOptions)
        {
            string          runText;
            XWPFRun         newRun;
            IList <XWPFRun> listRun = paragraph.Runs;

            if (TableOptions != null && TableOptions.dataTable != null && TableOptions.dataTable.Rows.Count > 0)
            {
                var nCls  = TableOptions.dataTable.Columns.Count;
                var nRows = TableOptions.dataTable.Rows.Count;

                for (int i = 0; i < listRun.Count; i++)
                {
                    XWPFRun run = listRun[i];
                    runText = run.Text;
                    if (run.Text == TableOptions.PlaceHolder.ToString())
                    {
                        paragraph.RemoveRun(i);
                        //newRun = paragraph.InsertNewRun(i);
                        //CT_Tbl cT_Tbl = doc.Document.body.AddNewTbl();
                        //XWPFTable tb = new XWPFTable(cT_Tbl, cell, nRows + 2, nCls);
                        var tb = doc.CreateTable(nRows + 2, nCls);
                        int j  = 0;
                        //tb.
                        foreach (DataColumn c in TableOptions.dataTable.Columns)
                        {
                            //var tbw=tb.GetRow(0).GetCell(j).GetCTTc();
                            //CT_TcPr ctPr = tbw.AddNewTcPr();                       //添加TcPr
                            //ctPr.tcW = new CT_TblWidth();
                            //ctPr.tcW.w = "200";//单元格宽
                            //ctPr.tcW.type = ST_TblWidth.dxa;
                            tb.GetRow(0).GetCell(j).SetColor("#AEAAAA");
                            XWPFParagraph pIO = tb.GetRow(0).GetCell(j).AddParagraph();
                            XWPFRun       rIO = pIO.CreateRun();
                            rIO.FontFamily = "宋体";
                            rIO.FontSize   = 11;
                            rIO.IsBold     = true;
                            //rIO.SetColor("#AEAAAA");
                            rIO.SetText(c.ColumnName);

                            //tb.GetRow(0).GetCell(j).SetColor("#AEAAAA");
                            //tb.GetRow(0).GetCell(j).SetText(c.ColumnName);
                            j++;
                        }
                        j = 0;
                        for (int n = 0; n < nRows; n++)
                        {
                            var dr = TableOptions.dataTable.Rows[n];
                            for (int m = 0; m < nCls; m++)
                            {
                                tb.GetRow(n + 1).GetCell(m).SetText(dr[m].ToString());
                            }
                        }
                    }
                }
            }
        }
        private XWPFParagraph _addLabelRun(XWPFParagraph paragraph, string text)
        {
            var run = paragraph.CreateRun();

            run.IsBold = true;
            run.SetText(text);
            run.AddTab();
            return(paragraph);
        }
Exemple #25
0
        private void AddCell(XWPFTableCell cell, string text)
        {
            XWPFParagraph paragraph = cell.AddParagraph();
            XWPFRun       run       = paragraph.CreateRun();

            run.SetText(text);
            run.FontFamily = "Times New Roman";
            run.FontSize   = 12;
        }
        /// <summary>
        /// 添加图片
        /// </summary>
        /// <param name="dc"></param>
        /// <param name="path"></param>
        public static void AddPicture(this XWPFDocument doc, string path, AddPictureType pType)
        {
            if (path.IndexOf("http") != -1)
            {
                //byte[] bytes = ExcelUtil.getFile(path);
                WebRequest   request  = WebRequest.Create(path);
                WebResponse  response = request.GetResponse();
                Stream       s        = response.GetResponseStream();
                byte[]       data     = new byte[response.ContentLength];
                int          length   = 0;
                MemoryStream ms       = new MemoryStream();
                while ((length = s.Read(data, 0, data.Length)) > 0)
                {
                    ms.Write(data, 0, length);
                }
                ms.Seek(0, SeekOrigin.Begin);

                //using (Stream stt = new MemoryStream(bytes))
                //{
                CT_P p = doc.GetNewP();
                p.SetAlign(ST_Jc.center);
                XWPFParagraph gp  = new XWPFParagraph(p, doc);
                XWPFRun       run = gp.CreateRun();
                run.AddPicture(ms, (int)PictureType.PNG, "2.png", 1000000, 1000000);
                ms.Close();
                //stt.Close();
                //}
            }
            //else if(path.IndexOf(";base64") != -1)
            //{
            //    int index = path.IndexOf(",");
            //    path = path.Substring(index + 1);
            //    byte[] bytes = Convert.FromBase64String(path);
            //    using (Stream s64 = new MemoryStream(bytes))
            //    {
            //        CT_P p = doc.GetNewP();
            //        p.SetAlign(ST_Jc.center);
            //        XWPFParagraph gp = new XWPFParagraph(p, doc);
            //        XWPFRun run = gp.CreateRun();
            //        run.AddPicture(s64, (int)PictureType.PNG, "1.png", 1000000, 1000000);
            //        s64.Close();
            //    }
            //}
            //else
            //{
            //    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
            //    {
            //        CT_P p = doc.GetNewP();
            //        p.SetAlign(ST_Jc.center);
            //        XWPFParagraph gp = new XWPFParagraph(p, doc);
            //        XWPFRun run = gp.CreateRun();
            //        run.AddPicture(fs, (int)PictureType.PNG, "1.png", 1000000, 1000000);
            //        fs.Close();
            //    }
            //}
        }
        public static XWPFRun CreateRun(this XWPFParagraph para, StyleConfig styles)
        {
            XWPFRun run = para.CreateRun();

            run.IsBold      = styles.isBold;
            run.IsItalic    = styles.isItalics;
            run.FontSize    = styles.fontSize;
            run.IsSmallCaps = styles.isSmallCaps;
            return(run);
        }
        private XWPFParagraph _addValueRun(XWPFParagraph paragraph, string text)
        {
            var run = paragraph.CreateRun();

            run.SetUnderline(UnderlinePatterns.Single);
            run.AddTab();
            run.SetText(text);
            run.AddTab();
            return(paragraph);
        }
        public void SaveTopicsToWord(Student student)
        {
            string resultpath = AppSetting.path + @"\StudentResult";

            if (!Directory.Exists(resultpath))
            {
                Directory.CreateDirectory(resultpath);
            }

            XWPFDocument doc = new XWPFDocument();

            {
                XWPFParagraph p = doc.CreateParagraph();
                p.Alignment = ParagraphAlignment.CENTER;

                XWPFRun r = p.CreateRun();
                r.SetText(SubjectEnum.ToString() + "试题");
                r.IsBold   = true;
                r.FontSize = 30;
            }
            {
                XWPFParagraph p1 = doc.CreateParagraph();   //向新文档中添加段落

                XWPFRun r1 = p1.CreateRun();                //向该段落中添加文字
                r1.SetText($"学号:{student.StudentID} 姓名:{student.Name} 机器码:{AppSetting.ComputerInfo}");
                r1.IsBold = true;
                XWPFParagraph p2 = doc.CreateParagraph();
            }
            {
                int index = 1;
                foreach (Topic t in Topics)
                {
                    XWPFParagraph p = doc.CreateParagraph();
                    {
                        XWPFRun r = p.CreateRun();
                        r.SetText(index + "." + t.Problem);
                        r.IsBold = true;
                        r.SetColor("255,0,0");
                    }
                    XWPFParagraph p2 = doc.CreateParagraph();
                    {
                        XWPFRun r = p2.CreateRun();
                        r.SetText(t.AnSwer);
                    }
                    XWPFParagraph p3 = doc.CreateParagraph();
                    index++;
                }
            }

            using (FileStream sw = File.Create(resultpath + GetFIleName(student) + ".docx"))
            {
                doc.Write(sw);
            }
            doc.Close();
        }
Exemple #30
0
        public string Run(int lineHight)
        {
            XWPFParagraph head      = this._doc.CreateParagraph();
            XWPFParagraph firstLine = this._doc.CreateParagraph();
            XWPFRun       firtRow   = firstLine.CreateRun();

            string line  = string.Empty;
            int    count = this._equations.Count;

            for (int i = 0; i < count + 1; i++)
            {
                if (i != 0 && i % 3 == 0 && i != count)
                {
                    XWPFParagraph p1 = this._doc.CreateParagraph();
                    XWPFRun       r1 = p1.CreateRun();
                    r1.SetText(line);
                    r1.SetTextPosition(10);
                    r1.SetFontFamily("Arial", FontCharRange.HAnsi);
                    r1.FontSize = 12;
                    if (lineHight > 0)
                    {
                        for (int k = 0; k <= lineHight; k++)
                        {
                            XWPFParagraph empty     = this._doc.CreateParagraph();
                            XWPFRun       emptyLine = empty.CreateRun();
                            emptyLine.SetText("   ");
                            emptyLine.SetTextPosition(10);
                        }
                    }
                    line = string.Empty;
                }
                if (i != count)
                {
                    line = line + string.Format("{0}) ", i + 1) + this._equations[i].Print() + "                             ";
                }
                else
                {
                    XWPFParagraph p1 = this._doc.CreateParagraph();
                    XWPFRun       r1 = p1.CreateRun();
                    r1.SetText(line);
                    r1.SetTextPosition(10);

                    r1.SetFontFamily("Arial", FontCharRange.HAnsi);
                    r1.FontSize = 12;
                }
            }
            string     fileName = DateTime.Now.ToShortDateString().Replace("/", "_") + (new Random()).Next().ToString();
            string     fullPath = string.Format("c:\\test\\{0}.docx", fileName);
            FileStream out1     = new FileStream(fullPath, FileMode.Create);

            this._doc.Write(out1);
            out1.Close();
            return(fullPath);
            //Process.Start(fullPath);
        }