示例#1
0
        public void Bug55802()
        {
            String blabla =
                "Bir, iki, \u00fc\u00e7, d\u00f6rt, be\u015f,\n" +
                "\nalt\u0131, yedi, sekiz, dokuz, on.\n" +
                "\nK\u0131rm\u0131z\u0131 don,\n" +
                "\ngel bizim bah\u00e7eye kon,\n" +
                "\nsar\u0131 limon";
            XWPFDocument doc = new XWPFDocument();
            XWPFRun      run = doc.CreateParagraph().CreateRun();

            foreach (String str in blabla.Split("\n".ToCharArray()))
            {
                run.SetText(str);
                run.AddBreak();
            }

            run.FontFamily = (/*setter*/ "Times New Roman");
            run.FontSize   = (/*setter*/ 20);
            Assert.AreEqual(run.FontFamily, "Times New Roman");
            Assert.AreEqual(run.GetFontFamily(FontCharRange.CS), "Times New Roman");
            Assert.AreEqual(run.GetFontFamily(FontCharRange.EastAsia), "Times New Roman");
            Assert.AreEqual(run.GetFontFamily(FontCharRange.HAnsi), "Times New Roman");
            run.SetFontFamily("Arial", FontCharRange.HAnsi);
            Assert.AreEqual(run.GetFontFamily(FontCharRange.HAnsi), "Arial");

            doc.Close();
        }
示例#2
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();
            }
        }
示例#3
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();
            }
        }
示例#4
0
        public void TestEnforcedWith()
        {
            XWPFDocument docx = XWPFTestDataSamples.OpenSampleDocument("EnforcedWith.docx");

            Assert.IsTrue(docx.IsEnforcedProtection());
            docx.Close();
        }
示例#5
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();
            }
        }
示例#6
0
 /// <summary>
 /// 替换文本标签
 /// </summary>
 /// <param name="strDataSourcePath">Word文件路径</param>
 /// <param name="strLabelName">标签名称(带标签符号)</param>
 /// <param name="strReplaceLabel">替换标签文本</param>
 /// <returns>成功返回替换数量,失败返回-1</returns>
 public static int ReplaceTextLabel(string strDataSourcePath, string strLabelName, string strReplaceLabel)
 {
     try
     {
         if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || string.IsNullOrEmpty(strReplaceLabel))
         {
             return(-1);
         }
         int          iNumber        = 0;
         FileStream   fileStreamOpen = new FileStream(strDataSourcePath, FileMode.Open, FileAccess.Read);
         XWPFDocument wordDocument   = new XWPFDocument(fileStreamOpen);
         foreach (XWPFParagraph wordParagraph in wordDocument.Paragraphs)
         {
             if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
             {
                 string strReplaceTextLabel = wordParagraph.ParagraphText.Replace(strLabelName, strReplaceLabel);
                 foreach (XWPFRun wordRun in wordParagraph.Runs)
                 {
                     wordRun.SetText(string.Empty, 0);
                 }
                 wordParagraph.CreateRun().SetText(strReplaceTextLabel, 0);
                 iNumber++;
             }
         }
         foreach (XWPFTable wordTable in wordDocument.Tables)
         {
             foreach (XWPFTableRow wordTableRow in wordTable.Rows)
             {
                 foreach (XWPFTableCell wordTableCell in wordTableRow.GetTableCells())
                 {
                     foreach (XWPFParagraph wordParagraph in wordTableCell.Paragraphs)
                     {
                         if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
                         {
                             string strReplaceTextLabel = wordParagraph.ParagraphText.Replace(strLabelName, strReplaceLabel);
                             foreach (XWPFRun wordRun in wordParagraph.Runs)
                             {
                                 wordRun.SetText(string.Empty, 0);
                             }
                             wordParagraph.CreateRun().SetText(strReplaceTextLabel, 0);
                             iNumber++;
                         }
                     }
                 }
             }
         }
         FileStream fileStreamSave = new FileStream(strDataSourcePath, FileMode.Create);
         wordDocument.Write(fileStreamSave);
         fileStreamSave.Close();
         wordDocument.Close();
         return(iNumber);
     }
     catch (Exception ex)
     {
         TXTHelper.Logs(ex.ToString());
         return(-1);
     }
 }
示例#7
0
 /// <summary>
 /// 替换表格标签(DataTable替换)
 /// </summary>
 /// <param name="strDataSourcePath">Word文件路径</param>
 /// <param name="strLabelName">标签名称(带标签符号)</param>
 /// <param name="dtReplaceLabel">替换标签DataTable</param>
 /// <returns>成功返回1,失败返回-1</returns>
 public static int ReplaceDataTableLabel(string strDataSourcePath, string strLabelName, DataTable dtReplaceLabel)
 {
     try
     {
         if (string.IsNullOrEmpty(strDataSourcePath) || !File.Exists(strDataSourcePath) || string.IsNullOrEmpty(strLabelName) || dtReplaceLabel == null || dtReplaceLabel.Rows.Count < 1)
         {
             return(-1);
         }
         FileStream   fileStreamOpen     = new FileStream(strDataSourcePath, FileMode.Open, FileAccess.Read);
         XWPFDocument wordDocument       = new XWPFDocument(fileStreamOpen);
         int          iLableRowPosition  = -1;
         int          iLableCellPosition = -1;
         foreach (XWPFTable wordTable in wordDocument.Tables)
         {
             for (int iTableRow = 0; iTableRow < wordTable.Rows.Count; iTableRow++)
             {
                 for (int iTableCell = 0; iTableCell < wordTable.Rows[iTableRow].GetTableCells().Count; iTableCell++)
                 {
                     foreach (XWPFParagraph wordParagraph in wordTable.Rows[iTableRow].GetTableCells()[iTableCell].Paragraphs)
                     {
                         if (wordParagraph.ParagraphText.IndexOf(strLabelName) >= 0)
                         {
                             if (iLableRowPosition < 0 && iLableCellPosition < 0)
                             {
                                 iLableRowPosition  = iTableRow;
                                 iLableCellPosition = iTableCell;
                             }
                         }
                         if (iLableRowPosition >= 0 && iLableCellPosition >= 0)
                         {
                             int iCurrentRow  = iTableRow - iLableRowPosition;
                             int iCurrentCell = iTableCell - iLableCellPosition;
                             if ((iCurrentRow < dtReplaceLabel.Rows.Count && iCurrentRow >= 0) && (iCurrentCell < dtReplaceLabel.Columns.Count && iCurrentCell >= 0))
                             {
                                 foreach (XWPFRun wordRun in wordParagraph.Runs)
                                 {
                                     wordRun.SetText(string.Empty, 0);
                                 }
                                 wordParagraph.CreateRun().SetText(dtReplaceLabel.Rows[iCurrentRow][iCurrentCell].ToString(), 0);
                             }
                         }
                     }
                 }
             }
         }
         FileStream fileStreamSave = new FileStream(strDataSourcePath, FileMode.Create);
         wordDocument.Write(fileStreamSave);
         fileStreamSave.Close();
         wordDocument.Close();
         return(1);
     }
     catch (Exception ex)
     {
         TXTHelper.Logs(ex.ToString());
         return(-1);
     }
 }
示例#8
0
 public Task <BookInfo> GetInfoAsync()
 {
     using (var file = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
     {
         var document = new XWPFDocument(file);
         var info     = GetInfo(document);
         document.Close();
         return(Task.FromResult(info));
     }
 }
        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();
        }
示例#10
0
        public void TestCreateFootnotes()
        {
            XWPFDocument  docOut    = new XWPFDocument();
            XWPFFootnotes footnotes = docOut.CreateFootnotes();

            Assert.IsNotNull(footnotes);
            XWPFFootnotes secondFootnotes = docOut.CreateFootnotes();

            Assert.AreSame(footnotes, secondFootnotes);
            docOut.Close();
        }
示例#11
0
 public Task <Book> GetBookAsync()
 {
     using (var file = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
     {
         var document = new XWPFDocument(file);
         var info     = GetInfo(document);
         var book     = new Book(info, document.Paragraphs.Select(p => p.Text));
         document.Close();
         return(Task.FromResult(book));
     }
 }
示例#12
0
        public void Save(string fileName)
        {
            if (!IsLoaded)
            {
                return;
            }

            var tempForSave = CreateTempFile();

            using (var fs = new FileStream(tempForSave, FileMode.OpenOrCreate, FileAccess.Write))
                doc.Write(fs);

            doc.Close();
            ReplaceFile(tempForSave, fileName);

            if (FileName == fileName)
            {
                File.Copy(FileName, SavedFileName, true);
            }

            doc = new XWPFDocument(OPCPackage.Open(FileName));
        }
示例#13
0
        public void Test59378()
        {
            XWPFDocument          doc  = XWPFTestDataSamples.OpenSampleDocument("59378.docx");
            ByteArrayOutputStream out1 = new ByteArrayOutputStream();

            doc.Write(out1);
            out1.Close();
            XWPFDocument doc2 = new XWPFDocument(new ByteArrayInputStream(out1.ToByteArray()));

            doc2.Close();
            XWPFDocument docBack = XWPFTestDataSamples.WriteOutAndReadBack(doc);

            docBack.Close();
        }
示例#14
0
        private void SaveFileAsWrod()
        {
            var doc = new XWPFDocument();

            list.ForEach(n => {
                var p1       = doc.CreateParagraph();
                p1.Alignment = ParagraphAlignment.LEFT;
                var runTitle = p1.CreateRun();
                if (Regex.IsMatch(n, @"^(\d)+、?"))
                {
                    runTitle.FontSize = 14;
                    runTitle.SetFontFamily("微软雅黑", FontCharRange.None);
                    runTitle.SetText(n.Trim() + "\r\n");
                }
                else if (n.Contains("参考答案"))
                {
                    runTitle.SetColor("#f00");
                    runTitle.FontSize = 14;
                    runTitle.SetText(n + "\r\n\r\n");
                }
                else if (!n.Equals("\r\n"))
                {
                    runTitle.SetText(n + "\r\n");
                }
            });
            //runTitle.FontSize = 12;
            //runTitle.SetFontFamily("微软雅黑", FontCharRange.None);
            //var ms = new MemoryStream();
            //doc.Write(ms);
            SaveFileDialog sfd = new SaveFileDialog();

            sfd.Title      = DateTimeKind.Local.ToString();
            sfd.Filter     = "Word Document(*.docx)|*.docx";
            sfd.DefaultExt = "Word Document(*.docx)|*.docx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                button1.Enabled = false;
                button3.Enabled = false;
                FileStream fs = (FileStream)sfd.OpenFile();
                doc.Write(fs);
                fs.Close();
                doc.Close();
                doc = null;
                fs  = null;
            }
            MessageBox.Show("保存成功");
            button1.Enabled = true;
            button3.Enabled = true;
        }
示例#15
0
        public AdminAwardsResp Awards(int smid)
        {
            AdminAwardsResp resp = new AdminAwardsResp();

            try
            {
                var result     = Fun.GetSqlConn().Query($"select sid, mid, awards from student_match where  id = {smid}");
                var sm_obj     = result.Single();
                var m_result   = Fun.GetSqlConn().Query($"select title from `match` where id = {sm_obj.mid}");
                var m_obj      = m_result.Single();
                var stu_result = Fun.GetSqlConn().Query($"select name from student where id = {sm_obj.sid}");
                var stu_obj    = stu_result.Single();

                // 生成证书
                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("荣誉证书");
                gr.SetText("——————");
                gr.SetText($"恭喜{stu_obj.name}同学在{m_obj.title}比赛中获得{sm_obj.awards},特发此证,予以鼓励!");
                FileStream fs = new FileStream(file_path, FileMode.OpenOrCreate, FileAccess.Write);
                doc.Write(fs);
                doc.Close();

                resp.status = 0;
                resp.msg    = "ok";
                resp.data   = Path.Combine("awards", unique_file_name);
            }
            catch (Exception ex)
            {
                resp.msg    = "未知错误" + ex.ToString();
                resp.status = -2;
                Console.WriteLine(resp.msg);
            }

            return(resp);
        }
示例#16
0
        static void Main(string[] args)
        {
            var templateFile    = "./../../../Doc1.docx";
            var destinationFile = "output.docx";

            using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read))
            {
                XWPFDocument wordDoc = new XWPFDocument(file);

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

                wordDoc.Write(fs);
                fs.Close();

                wordDoc.Close();
            }
        }
示例#17
0
        public void TestSetStyleId()
        {
            XWPFDocument document = XWPFTestDataSamples.OpenSampleDocument("SampleDoc.docx");

            XWPFRun run = document.CreateParagraph().CreateRun();

            String styleId = "bolditalic";

            run.SetStyle(styleId);
            String candStyleId = run.GetCTR().rPr.rStyle.val;

            Assert.IsNotNull(candStyleId, "Expected to find a run style ID");
            Assert.AreEqual(styleId, candStyleId);

            Assert.AreEqual(styleId, run.GetStyle());

            document.Close();
        }
示例#18
0
        public void TestTransitiveSetters()
        {
            XWPFDocument   doc = new XWPFDocument();
            CoreProperties cp  = doc.GetProperties().CoreProperties;

            DateTime dateCreated = new DateTime(2010, 6, 15, 10, 0, 0);

            cp.Created = new DateTime(2010, 6, 15, 10, 0, 0);
            Assert.AreEqual(dateCreated.ToString(), cp.Created.ToString());

            XWPFDocument doc2 = XWPFTestDataSamples.WriteOutAndReadBack(doc);

            doc.Close();
            cp = doc2.GetProperties().CoreProperties;
            DateTime?dt3 = cp.Created;

            Assert.AreEqual(dateCreated.ToString(), dt3.ToString());

            doc2.Close();
        }
示例#19
0
 /// <summary>
 /// 创建Word(Office2007)
 /// </summary>
 /// <param name="strDataSourcePath">新建Word的路径.doc</param>
 /// <returns>成功返回true,失败返回false</returns>
 public static bool CreateWord_Office2007(string strDataSourcePath)
 {
     try
     {
         if (string.IsNullOrEmpty(strDataSourcePath))
         {
             return(false);
         }
         XWPFDocument Word2007       = new XWPFDocument();
         FileStream   fileStream2007 = new FileStream(Path.ChangeExtension(strDataSourcePath, "docx"), FileMode.Create);
         Word2007.Write(fileStream2007);
         fileStream2007.Close();
         Word2007.Close();
         return(true);
     }
     catch (Exception ex)
     {
         TXTHelper.Logs(ex.ToString());
         return(false);
     }
 }
示例#20
0
        public void TestBug55476()
        {
            byte[]       image    = XWPFTestDataSamples.GetImage("abstract1.jpg");
            XWPFDocument document = new XWPFDocument();

            document.CreateParagraph().CreateRun().AddPicture(
                new MemoryStream(image), (int)PictureType.JPEG, "test.jpg", Units.ToEMU(300), Units.ToEMU(100));
            XWPFDocument       docBack  = XWPFTestDataSamples.WriteOutAndReadBack(document);
            List <XWPFPicture> pictures = docBack.GetParagraphArray(0).Runs[0].GetEmbeddedPictures();

            Assert.AreEqual(1, pictures.Count);
            docBack.Close();

            /*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx");
             * try {
             *  document.write(stream);
             * } finally {
             *  stream.close();
             * }*/
            document.Close();
        }
示例#21
0
        // 给表格追加行
        static void Main4312()
        {
            string inputPath = @"C:\Users\Wesley\source\dotnetCore\UselessProjects\testExcel\userfile\a.docx";
            string outpath   = @"C:\Users\Wesley\source\dotnetCore\UselessProjects\testExcel\userfile\c.docx";

            XWPFDocument doc = null;

            using (FileStream fs = new FileStream(inputPath, FileMode.Open, FileAccess.Read))
            {
                doc = new XWPFDocument(fs);
            }

            // doc.InsertTable()
            UpdateTable(doc.Tables[0]);


            FileStream file = new FileStream(outpath, FileMode.Create, FileAccess.Write);

            doc.Write(file);
            file.Close();
            doc.Close();
        }
示例#22
0
        /// <summary>
        /// This Functions Erases the Docx File and create a new one, using the
        /// simpleXml generated by the TransformToSimpleXml() method.
        /// </summary>
        /// <param name="docLocation"></param>
        /// <param name="simplerXml"></param>
        private static void ReWriteDocument(string docLocation, XElement simplerXml)
        {
            string newDocLocation = docLocation.Split('.')[0] + " Simplificado.docx";

            using (FileStream fileStream = new FileStream(newDocLocation, FileMode.Create, FileAccess.Write))
            {
                XWPFDocument newWordDoc = new XWPFDocument();

                foreach (XElement paragraph in simplerXml.Elements())
                {
                    XWPFParagraph newDocParagraph = newWordDoc.CreateParagraph();
                    newDocParagraph.Alignment = ParagraphAlignment.LEFT;
                    XWPFRun newDocRun = newDocParagraph.CreateRun();
                    newDocRun.FontFamily = "Arial";
                    newDocRun.FontSize   = 12;
                    newDocRun.IsBold     = false;
                    newDocRun.SetText(paragraph.Value);
                }

                newWordDoc.Write(fileStream);
                newWordDoc.Close();
            }
        }
示例#23
0
        public void Run()
        {
            var    templateFileName = @"templates\template.docx";
            string path             = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), $"{templateFileName}");
            var    currentTime      = DateTime.Now;
            var    outputFileName   = String.Format("{0} {1} {2}.{3}.{4}.docx",
                                                    "output", currentTime.ToShortDateString(), currentTime.Hour, currentTime.Minute, currentTime.Second);

            XWPFDocument doc;

            FillPersonInfo();

            try
            {
                using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    doc = new XWPFDocument(fileStream);
                    fileStream.Close();
                }

                ReplaceData(doc, PersonInfo);

                using (FileStream fileStreamNew = new FileStream(outputFileName, FileMode.CreateNew))
                {
                    doc.Write(fileStreamNew);
                    fileStreamNew.Close();
                }

                doc.Close();

                Console.WriteLine("Done");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
示例#24
0
 public void closeResources()
 {
     sampleDoc.Close();
     sampleNoThumb.Close();
 }
示例#25
0
        private ReturnMessage WriteDoc()
        {
            ReturnMessage retMsg = new ReturnMessage(string.Empty, true);
            FileStream    fs     = null;

            try
            {
                XWPFDocument doc   = new XWPFDocument();
                XWPFTable    table = null;
                int          index = 1;
                foreach (DataRow dr in dtInfo.Rows)
                {
                    if (dr["表名"] != DBNull.Value && !string.IsNullOrEmpty(dr["表名"].ToString()))
                    {
                        //表名,以段落表示
                        CT_P ctp = doc.Document.body.AddNewP();
                        //XWPFParagraph p = doc.CreateParagraph();
                        XWPFParagraph p = new XWPFParagraph(ctp, doc);
                        XWPFRun       r = p.CreateRun();
                        //设置字体
                        r.GetCTR().AddNewRPr().AddNewRFonts().ascii    = "宋体";
                        r.GetCTR().AddNewRPr().AddNewRFonts().eastAsia = "宋体";
                        r.GetCTR().AddNewRPr().AddNewRFonts().hint     = ST_Hint.eastAsia;
                        r.GetCTR().AddNewRPr().AddNewSz().val          = (ulong)32;//3号字体;
                        r.GetCTR().AddNewRPr().AddNewSzCs().val        = (ulong)32;
                        //设置行间距
                        //单倍为默认值(240twip)不需设置,1.5倍=240X1.5=360twip,2倍=240X2=480twip
                        ctp.AddNewPPr().AddNewSpacing().line = "720";
                        //ctp.AddNewPPr().AddNewSpacing().lineRule = ST_LineSpacingRule.exact;
                        //设置段落文本
                        r.SetText(index.ToString() + "." + dr["表名"].ToString());

                        //表结构,以表格显示
                        CT_Tbl m_CTTbl = doc.Document.body.AddNewTbl();
                        table = doc.CreateTable(1, 9);
                        //标题行(固定)
                        //列宽
                        CT_TcPr mPr = table.GetRow(0).GetCell(0).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "900";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(1).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "1500";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(2).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "500";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(3).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "1000";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(4).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "500";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(6).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "900";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(7).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "800";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        mPr          = table.GetRow(0).GetCell(8).GetCTTc().AddNewTcPr();
                        mPr.tcW      = new CT_TblWidth();
                        mPr.tcW.w    = "1500";
                        mPr.tcW.type = ST_TblWidth.dxa;
                        //填充文字
                        table.GetRow(0).GetCell(0).SetText("字段序号");
                        table.GetRow(0).GetCell(1).SetText("字段名");
                        table.GetRow(0).GetCell(2).SetText("主键");
                        table.GetRow(0).GetCell(3).SetText("类型");
                        table.GetRow(0).GetCell(4).SetText("长度");
                        table.GetRow(0).GetCell(5).SetText("精度");
                        table.GetRow(0).GetCell(6).SetText("小数位数");
                        table.GetRow(0).GetCell(7).SetText("允许空");
                        table.GetRow(0).GetCell(8).SetText("字段说明");
                        //内容行
                        XWPFTableRow row = table.CreateRow();
                        row.GetCell(0).SetText(dr["字段序号"].ToString());
                        row.GetCell(1).SetText(dr["字段名"].ToString());
                        row.GetCell(2).SetText(dr["主键"].ToString());
                        row.GetCell(3).SetText(dr["类型"].ToString());
                        row.GetCell(4).SetText(dr["长度"].ToString());
                        row.GetCell(5).SetText(dr["精度"].ToString());
                        row.GetCell(6).SetText(dr["小数位数"].ToString());
                        row.GetCell(7).SetText(dr["允许空"].ToString());
                        row.GetCell(8).SetText("");
                        //
                        index++;
                    }
                    else
                    {
                        if (table != null)
                        {
                            //内容行
                            XWPFTableRow row = table.CreateRow();
                            row.GetCell(0).SetText(dr["字段序号"].ToString());
                            row.GetCell(1).SetText(dr["字段名"].ToString());
                            row.GetCell(2).SetText(dr["主键"].ToString());
                            row.GetCell(3).SetText(dr["类型"].ToString());
                            row.GetCell(4).SetText(dr["长度"].ToString());
                            row.GetCell(5).SetText(dr["精度"].ToString());
                            row.GetCell(6).SetText(dr["小数位数"].ToString());
                            row.GetCell(7).SetText(dr["允许空"].ToString());
                            row.GetCell(8).SetText("");
                        }
                    }
                }
                //输出保存
                string docAllPath = Application.StartupPath + "\\SqlDBDicFile.docx";
                if (File.Exists(docAllPath))
                {
                    File.Delete(docAllPath);
                }
                fs = File.OpenWrite(docAllPath);
                doc.Write(fs);
                doc.Close();
                return(retMsg);
            }
            catch (Exception ex)
            {
                retMsg.isSuccess = false;
                retMsg.Messages  = ex.Message;
                return(retMsg);
            }
            finally
            {
                fs.Close();
                fs.Dispose();
            }
        }
        /// <summary>
        /// 按模板生成 Word 文档
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="templatePath">模板路径</param>
        /// <param name="wordPath">Word 路径</param>
        /// <param name="dataMatchList">数据匹配,Dictionary&lt;string, object&gt; 或 new {}</param>
        public static void ToWord(string templatePath, string wordPath, object dataMatchList)
        {
            FileStream   fileStream = null;
            XWPFDocument document   = null;

            try
            {
                using (fileStream = File.OpenRead(templatePath))
                {
                    document = new XWPFDocument(fileStream);
                }

                IList <XWPFTableRow>  rowItemList   = null;
                IList <XWPFTableCell> cellItemList  = null;
                IList <XWPFTable>     tableItemList = document.Tables;

                List <XWPFParagraph> paragraphItemList = new List <XWPFParagraph>();
                paragraphItemList.AddRange(document.Paragraphs);

                #region 处理表格数据
                if (tableItemList != null && tableItemList.Count > 0)
                {
                    foreach (XWPFTable tableItem in tableItemList)
                    {
                        rowItemList = tableItem.Rows;
                        if (rowItemList != null && rowItemList.Count > 0)
                        {
                            foreach (XWPFTableRow rowItem in rowItemList)
                            {
                                cellItemList = rowItem.GetTableCells();
                                if (cellItemList != null && cellItemList.Count > 0)
                                {
                                    foreach (XWPFTableCell cellItem in cellItemList)
                                    {
                                        paragraphItemList.AddRange(cellItem.Paragraphs);
                                    }
                                }
                            }
                        }
                    }
                }
                #endregion

                #region 处理段落数据
                if (paragraphItemList != null && paragraphItemList.Count > 0)
                {
                    Dictionary <string, object> dataDict = CommonHelper.GetParameterDict(dataMatchList);
                    foreach (XWPFParagraph paragraph in paragraphItemList)
                    {
                        ExecuteReplaceParagraph(paragraph, dataDict);
                    }
                }
                #endregion

                if (System.IO.File.Exists(wordPath))
                {
                    System.IO.File.Delete(wordPath);
                }
                using (fileStream = new FileStream(wordPath, FileMode.Create, FileAccess.Write))
                {
                    document.Write(fileStream);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
示例#27
0
        public void Write()
        {
            XWPFDocument mydoc = new XWPFDocument();

            //设置页面大小
            CT_SectPr size = new CT_SectPr();

            size.pgSz.w = 11900;
            size.pgSz.h = 16830;
            mydoc.Document.body.sectPr = size;

            //创建段落
            XWPFParagraph p1 = mydoc.CreateParagraph();

            //设置段落样式
            p1.Alignment = ParagraphAlignment.CENTER;//居中
            XWPFRun run1 = p1.CreateRun();
            XWPFRun run3 = p1.CreateRun();

            run3.SetText("测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试测试");
            run1.FontSize = 16;       //设置字体大小
            run1.SetColor("#808080"); //设置字体颜色
            run1.SetText("标题文本标题文本标题文本标题文本标题文本");

            //创建段落
            XWPFParagraph p2 = mydoc.CreateParagraph();

            p2.Alignment = ParagraphAlignment.CENTER;//居中
            XWPFRun run2 = p2.CreateRun();

            run2.SetColor("#123456");
            run2.FontSize = 8;
            run2.SetText("时间:" + DateTime.Now.ToString());

            //获取数据
            DataSet   set   = GetData();
            DataTable table = set.Tables[0];
            //创建表单
            XWPFTable table1 = mydoc.CreateTable(table.Rows.Count + 1, table.Columns.Count);

            //设置第一行表格
            XWPFTableCell firstcell1 = table1.GetRow(0).GetCell(0);

            //XWPFRun firstcell1 = t1.CreateRun();
            firstcell1.SetColor("#FF0000");
            firstcell1.SetText("name1");

            XWPFTableCell firstcell2 = table1.GetRow(0).GetCell(1);

            //XWPFRun firstcell2 = t2.CreateRun();
            firstcell2.SetColor("#FF0000");
            firstcell2.SetText("name2");

            XWPFTableCell firstcell3 = table1.GetRow(0).GetCell(2);

            //XWPFRun firstcell3 = t3.CreateRun();
            firstcell3.SetColor("#FF0000");
            firstcell3.SetText("id");

            /**
             * 这些单元格默认换行
             */
            for (int row = 0; row < table.Rows.Count; row++)
            {
                for (int colum = 0; colum < table.Columns.Count; colum++)
                {
                    table1.GetRow(row + 1).Height = 10;
                    XWPFParagraph t   = table1.GetRow(row + 1).GetCell(colum).AddParagraph();
                    XWPFRun       rIO = t.CreateRun();
                    rIO.FontSize = 5;
                    rIO.IsBold   = true;
                    rIO.SetText(table.Rows[row][colum].ToString());
                }
            }

            //行合并
            //table1.GetRow(2).MergeCells(0, 1);


            FileStream stream = new FileStream(filename, FileMode.Create);

            mydoc.Write(stream);
            stream.Close();
            mydoc.Close();
        }
示例#28
0
 public void Close()
 {
     doc.Close();
 }
        private void BtnExportClick(object sender, RoutedEventArgs e)
        {
            if (_FixedDoc == null)
            {
                this.BtnExport.IsEnabled = false;
                return;
            }
            System.Windows.Forms.SaveFileDialog fileDialog = new System.Windows.Forms.SaveFileDialog();
            fileDialog.Filter   = "Docx|*.Docx";
            fileDialog.FileName = _FixedDocVM.CurMember.Name;
            if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            try
            {
                this.BtnExport.IsEnabled = false;
                string MemberTemplet = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "OWPMemberInfo.dat");
                if (!File.Exists(MemberTemplet))
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("未找到欲导出的模板文件!", Caption: "失败");
                    return;
                }
                FileStream FStream = File.OpenRead(MemberTemplet);
                if (FStream == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("读取模板文件时出现错误,是否文件正在使用?", Caption: "失败");
                    return;
                }
                InputStream WordStream = new FileInputStream(FStream);
                if (WordStream == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("转换模板文件成Word对象流时出现错误?", Caption: "失败");
                    return;
                }
                XWPFDocument WDoc = new XWPFDocument(WordStream);
                if (WDoc == null)
                {
                    this.BtnExport.IsEnabled = true;
                    AppFuns.ShowMessage("转换模板文件成Word对象时出现错误?", Caption: "失败");
                    return;
                }
                //释放不必须的资源
                FStream.Dispose();
                WordStream.Dispose();

                //开始导出
                ExportWord(WDoc, _FixedDocVM);

                //写入输出文件
                if (WDoc != null)
                {
                    FileStream NewWordDoc = File.Create(fileDialog.FileName);
                    WDoc.Write(NewWordDoc);
                    NewWordDoc.Close();
                    WDoc.Close();
                    AppFuns.ShowMessage("数据导出成功!", Caption: "完成");
                    FileOperation.UseDefaultAppOpenFile(fileDialog.FileName);
                }
                else
                {
                    AppFuns.ShowMessage("数据导出失败!", Caption: "失败");
                }
                this.BtnExport.IsEnabled = true;
            }
            catch (Exception Ex)
            {
                this.BtnExport.IsEnabled = true;
                AppFuns.ShowMessage(Ex.Message, Caption: "失败");
            }
        }