Example #1
0
        static void Main(string[] args)
        {
            XWPFDocument document     = new XWPFDocument();
            XWPFTable    tableOne     = document.CreateTable();
            XWPFTableRow tableOneRow1 = tableOne.GetRow(0);
            XWPFTableRow tableOneRow2 = tableOne.CreateRow();

            tableOneRow1.GetCell(0).SetText("Test11");
            tableOneRow1.AddNewTableCell();
            tableOneRow1.GetCell(1).SetText("Test12");
            tableOneRow2.GetCell(0).SetText("Test21");
            tableOneRow2.AddNewTableCell();

            XWPFTableCell cell  = tableOneRow2.GetCell(1);
            var           ctTbl = cell.GetCTTc().AddNewTbl();

            //to remove the line from the cell, you can call cell.removeParagraph(0) instead
            cell.SetText("line1");
            cell.GetCTTc().AddNewP();

            XWPFTable    tableTwo     = new XWPFTable(ctTbl, cell);
            XWPFTableRow tableTwoRow1 = tableTwo.GetRow(0);

            tableTwoRow1.GetCell(0).SetText("nestedTable11");
            tableTwoRow1.AddNewTableCell();
            tableTwoRow1.GetCell(1).SetText("nestedTable12");

            using (FileStream fs = new FileStream("nestedTable.docx", FileMode.Create))
            {
                document.Write(fs);
            }
        }
Example #2
0
        private void FileChange(XWPFDocument doc)
        {
            string title = @"{合同名称}";
            IList <XWPFParagraph> paragraphs = doc.Paragraphs;

            foreach (XWPFParagraph item in paragraphs)
            {
                foreach (XWPFRun xwprun in item.Runs)
                {
                    if (xwprun.Text.Contains(title))
                    {
                        xwprun.ReplaceText(title, "艾勇的合同");
                    }
                }
            }
            IList <XWPFTable> tables = doc.Tables;

            foreach (XWPFTable table in tables)
            {
                XWPFTableRow row = table.Rows.FirstOrDefault();

                for (int i = 0; i < 10; i++)
                {
                    XWPFTableRow xWPFTableRow = table.CreateRow();
                    for (int j = 0; j < row.GetTableCells().Count; j++)
                    {
                        XWPFTableCell rowCell = xWPFTableRow.GetCell(j);
                        if (j == 0)
                        {
                            rowCell.SetText("张三" + i);
                        }
                        else
                        {
                            rowCell.SetText(i.ToString());
                        }
                    }
                }
            }
        }
 //创建“评估结果”表格表头部分
 void CreateAssessmentResultHeaderAndSetValue(XWPFTable table, out CT_Row m_NewRow, out XWPFTableRow m_Row, out XWPFTableCell cell, out CT_Tc cttc, out CT_TcPr ctPr)
 {
     DealWithMergeCell(table, out m_NewRow, out m_Row, out cell, out cttc, out ctPr);
     StartMergeRow(cttc, ctPr, "评估结果");
     cell = m_Row.CreateCell();
     SetBoldFontCell(cell, "评估项目");
     SetAlign(cell);
     cell = m_Row.CreateCell();
     SetBoldFontCell(cell, "评估结论");
     SetAlign(cell);
     cell = m_Row.CreateCell();
     cell.SetText("");
     SetAlign(cell);
     cell = m_Row.CreateCell();
     SetBoldFontCell(cell, "建议");
     SetAlign(cell);
 }
Example #4
0
        // word 添加表格, 表格的行宽怎么确定
        public static void AddTable(XWPFDocument doc, DataTable dt)
        {
            // XWPFDocument doc = new XWPFDocument();
            //创建表格-提前创建好表格后填数
            XWPFTable table = doc.CreateTable();//4行5列

            int rowCount = dt.Rows.Count + 1;
            int colCount = dt.Columns.Count;

            XWPFTableRow titles = table.GetRow(0);

            // table.AddRow(titles);
            for (int i = 0; i < colCount; i++)
            {
                string        title = dt.Columns[i].ColumnName;
                XWPFTableCell cell  = titles.GetCell(i);
                if (cell == null)
                {
                    cell = titles.CreateCell();
                }
                // cell.SetParagraph(SetCellText(doc, table, title));
                cell.SetText(title);
            }

            for (int i = 1; i < rowCount; i++)//有3个数组
            {
                DataRow      dr       = dt.Rows[i - 1];
                XWPFTableRow tablerow = table.CreateRow();
                // XWPFTableRow tablerow = table.GetRow(i);
                for (int j = 0; j < colCount; j++)
                {
                    string content = dr[j].ToString();
                    // tablerow.GetCell(j).SetParagraph(SetCellText(doc, table, content));

                    tablerow.GetCell(j).SetText(content);
                }
                //    table.AddRow(tablerow);
            }
        }
Example #5
0
        // word 给表格追加行, 下标对应
        public static void AppendTable(XWPFTable table, DataTable newDatas)
        {
            //创建表格-提前创建好表格后填数

            int rowCount = newDatas.Rows.Count;
            int colCount = newDatas.Columns.Count;

            for (int i = 0; i < rowCount; i++)
            {
                XWPFTableRow row = table.CreateRow();

                for (int j = 0; j < colCount; j++)
                {
                    XWPFTableCell cell = row.GetCell(j);
                    if (cell == null)
                    {
                        cell = row.CreateCell();
                    }
                    string content = newDatas.Rows[i][j]?.ToString();
                    cell.SetText(content);
                }
            }
        }
Example #6
0
        private static Model ParseFile(string basePath, string filename, string[] fields)
        {
            int[][] cells = new int[13][] {
                new int[2] {
                    0, 1
                }, new int[2] {
                    0, 3
                }, new int[2] {
                    1, 1
                },
                new int[2] {
                    1, 3
                }, new int[2] {
                    0, 5
                }, new int[2] {
                    1, 5
                },
                new int[2] {
                    2, 1
                }, new int[2] {
                    6, 5
                }, new int[2] {
                    7, 5
                },
                new int[2] {
                    6, 1
                }, new int[2] {
                    2, 5
                }, new int[2] {
                    3, 3
                },
                new int[2] {
                    2, 3
                }
            };
            Stream       stream = File.OpenRead(filename);
            XWPFDocument doc    = new XWPFDocument(stream);
            XWPFTable    table  = doc.GetTableArray(0);
            Model        model  = new Model();

            PropertyInfo[] properties = model.GetType().GetProperties();
            for (int i = 0; i < cells.Length; i++)
            {
                int[]         c    = cells[i];
                XWPFTableRow  row  = table.GetRow(c[0]);
                XWPFTableCell cell = row.GetCell(c[1]);
                string        text = cell.GetText();
                if (fields[i] == "minzu" && !text.EndsWith("族")) // 汉 改为 汉族
                {
                    text = text + "族";
                    cell.SetText(text);
                }
                if (fields[i] == "jiguan" && !text.Contains("省")) // 河南洛阳 改为 河南省洛阳市
                {
                    text = text.Substring(0, 2) + "省" + text.Substring(2, 2) + "市";
                    cell.SetText(text);
                }
                foreach (PropertyInfo t in properties)
                {
                    if (t.Name == fields[i])
                    {
                        t.SetValue(model, text);
                        break;
                    }
                }
            }
            string outputdoc = Path.Combine(basePath, "神经内科", Path.GetFileName(filename));

            doc.Write(File.OpenWrite(outputdoc));
            model.company = "洛阳市第三人民医院";
            model.area    = "洛阳市瀍河区";
            stream.Close();
            return(model);
        }
Example #7
0
        /// <summary>
        /// 将行拷贝到目标表格
        /// 只拷贝了基本的样式
        /// </summary>
        /// <param name="targetTable">目标表格</param>
        /// <param name="sourceRow">源表格行</param>
        /// <param name="rowIndex">行索引</param>
        /// <param name="maxCol">表格最大列数</param>
        public static void CopyRowToTable(XWPFTable targetTable, XWPFTableRow sourceRow, int rowIndex, int maxCol)
        {
            //在表格指定位置新增一行
            XWPFTableRow targetRow = rowIndex == 0 ? targetTable.GetRow(0) : targetTable.CreateRow();

            //复制行属性
            targetRow.GetCTRow().trPr     = sourceRow.GetCTRow().trPr;
            List <XWPFTableCell> cellList = sourceRow.GetTableCells();

            if (null == cellList)
            {
                return;
            }
            //复制列及其属性和内容
            int colIndex = 0;

            foreach (XWPFTableCell sourceCell in cellList)
            {
                XWPFTableCell targetCell = null;
                //新增行会默认有一个单元格,因此直接获取就好
                try
                {
                    targetCell = targetRow.GetCell(colIndex);
                }
                catch (Exception)
                {
                }

                if (targetCell == null)
                {
                    targetCell = targetRow.CreateCell();
                }

                //列属性
                targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr;

                //段落属性
                if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0)
                {
                    var paragraph = targetCell.Paragraphs[0];
                    var ctp       = (CT_P)typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(paragraph);

                    var sourceParagraph = sourceCell.Paragraphs[0];
                    var sourceCtp       = (CT_P)typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sourceParagraph);

                    paragraph.Alignment = sourceParagraph.Alignment;
                    ctp.pPr             = sourceCtp.pPr;

                    if (sourceCell.Paragraphs[0].Runs != null && sourceCell.Paragraphs[0].Runs.Count > 0)
                    {
                        XWPFRun cellR  = targetCell.Paragraphs[0].CreateRun();
                        var     srcRun = sourceCell.Paragraphs[0].Runs[0];
                        cellR.SetText(sourceCell.GetText());
                        cellR.IsBold = srcRun.IsBold;
                        cellR.SetColor(srcRun.GetColor());
                        cellR.FontFamily            = srcRun.FontFamily;
                        cellR.IsCapitalized         = srcRun.IsCapitalized;
                        cellR.IsDoubleStrikeThrough = srcRun.IsDoubleStrikeThrough;
                        cellR.IsEmbossed            = srcRun.IsEmbossed;
                        cellR.IsImprinted           = srcRun.IsImprinted;
                        cellR.IsItalic   = srcRun.IsItalic;
                        cellR.IsShadowed = srcRun.IsShadowed;
                    }
                    else
                    {
                        targetCell.SetText(sourceCell.GetText());
                    }
                }
                else
                {
                    targetCell.SetText(sourceCell.GetText());
                }

                colIndex++;
            }

            if (cellList.Count < maxCol)
            {
                try
                {
                    targetRow.MergeCells(cellList.Count - 1, maxCol - 1);
                }
                catch
                {
                }
            }
        }
Example #8
0
        public void Begin(WorldField worldField, XWPFDocument doc)
        {
            if (worldField.FieldSourceList == null || worldField.FieldSourceList.Count <= 0)
            {
                throw new Exception("请先配置导出数据源");
            }
            var modelField = worldField.FieldSourceList.Where(it => it.SoucreType == SoucreType.Entity);

            if ((modelField?.Count() ?? 0) > 1)
            {
                throw new Exception("只能配置一个主体表信息");
            }
            //主体的字段信息替换
            if (modelField != null)
            {
                var       baseModel = modelField.FirstOrDefault();
                string    executSql = baseModel.SourceSql.Replace("{oid}", $"'{worldField.Oid}'");
                DataTable dataTable = new DataTable();
                using (SqlConnection conn = GetSqlConnection())
                {
                    dataTable.Load(conn.ExecuteReader(executSql));
                }
                if (dataTable.Rows.Count <= 0)
                {
                    throw new Exception("主题信息查询失败");
                }

                DataRow row = dataTable.Rows[0];

                List <Field> fieldList = GetFieldList(dataTable.Columns, "");

                IList <XWPFParagraph> paragraphs = doc.Paragraphs;
                foreach (XWPFParagraph xwpParagraph in paragraphs)
                {
                    foreach (XWPFRun xwprun in xwpParagraph.Runs)
                    {
                        string text = xwprun.Text.Clone().ToString();
                        if (text.Contains("加成率"))
                        {
                        }
                        foreach (Field field in fieldList)
                        {
                            if (xwprun.Text.Contains(field.SignName))
                            {
                                text = text.Replace(field.SignName, row[field.Name].ToString());
                            }
                        }
                        xwprun.ReplaceText(xwprun.Text, text);
                    }
                }
            }
            //可重复表数量
            List <FieldSource> tableSource = worldField.FieldSourceList.Where(it => it.SoucreType == SoucreType.List)?.ToList() ?? new List <FieldSource>();


            IList <XWPFTable> tables = doc.Tables;


            foreach (FieldSource item in tableSource)
            {
                string executSql = item.SourceSql.Replace("{oid}", $"'{worldField.Oid}'");

                DataTable dataTable = new DataTable();
                using (SqlConnection conn = GetSqlConnection())
                {
                    dataTable.Load(conn.ExecuteReader(executSql));
                }
                if (dataTable.Rows.Count <= 0)
                {
                    throw new Exception("数据查询失败");
                }
                List <Field> fieldList = GetFieldList(dataTable.Columns, item.TableName);

                //具体的表处理
                foreach (XWPFTable table in tables)
                {
                    XWPFTableRow row = table.Rows.FirstOrDefault();

                    Dictionary <int, string> dicTitle = GetTableField(row, item.TableName, fieldList);
                    if (dicTitle.Count <= 0)
                    {
                        continue;
                    }

                    foreach (DataRow dataRow in dataTable.Rows)
                    {
                        XWPFTableRow xWPFTableRow = table.CreateRow();
                        foreach (var title in dicTitle)
                        {
                            string columnName = fieldList.FirstOrDefault(it => it.SignName.Equals(title.Value))?.Name;
                            if (string.IsNullOrEmpty(columnName))
                            {
                                continue;
                            }
                            XWPFTableCell rowCell = xWPFTableRow.GetCell(title.Key);
                            rowCell.SetText(dataRow[columnName].ToString());
                        }
                    }
                }
            }
        }
Example #9
0
        /// <summary>
        /// 复制一行到指定位置
        /// 样式信息也复制了,但需要完善。
        /// </summary>
        /// <param name="sourceRow"></param>
        /// <param name="table"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        public static XWPFTableRow CopyRow(XWPFTableRow sourceRow, XWPFTable table, int rowIndex)
        {
            //在表格指定位置新增一行
            var needRemove = false;

            if (table.NumberOfRows <= rowIndex)
            {
                table.CreateRow();
                needRemove = true;
            }
            XWPFTableRow targetRow = table.InsertNewTableRow(rowIndex);

            if (needRemove)
            {
                table.RemoveRow(rowIndex + 1);
            }

            //复制行属性
            targetRow.GetCTRow().trPr        = sourceRow.GetCTRow().trPr;
            List <XWPFTableCell> sourceCells = sourceRow.GetTableCells();

            if (null == sourceCells)
            {
                return(targetRow);
            }
            //复制列及其属性和内容
            foreach (var sourceCell in sourceCells)
            {
                XWPFTableCell targetCell = targetRow.AddNewTableCell();
                targetCell.RemoveParagraph(0);//新建cell会自动创建paragraph,将其删除,下面代码循环添加

                //列属性
                targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr;

                //段落属性
                if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0)
                {
                    foreach (var sourcePa in sourceCell.Paragraphs)
                    {
                        if (sourcePa.Runs != null && sourcePa.Runs.Count > 0)
                        {
                            var targetPa = targetCell.AddParagraph();
                            targetPa.Alignment = sourcePa.Alignment;
                            foreach (var srcR in sourcePa.Runs)
                            {
                                XWPFRun tarR = targetPa.CreateRun();
                                tarR.SetText(srcR.Text);
                                tarR.SetTextPosition(srcR.GetTextPosition());
                                tarR.FontFamily    = srcR.FontFamily;
                                tarR.FontSize      = srcR.FontSize <= 0 ? 12 : srcR.FontSize;
                                tarR.IsBold        = srcR.IsBold;
                                tarR.IsItalic      = srcR.IsItalic;
                                tarR.IsCapitalized = srcR.IsCapitalized;
                                tarR.SetColor(srcR.GetColor());
                                tarR.SetUnderline(srcR.Underline);
                                tarR.CharacterSpacing = srcR.CharacterSpacing;
                            }
                        }
                        else
                        {
                            targetCell.SetText(sourceCell.GetText());
                        }
                    }
                }
                else
                {
                    targetCell.SetText(sourceCell.GetText());
                }
            }
            return(targetRow);
        }
Example #10
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();
        }
Example #11
0
        private static XWPFParagraph ReplaceParagraph(XWPFParagraph p, Dictionary <string, object> data, XWPFTableCell cell)
        {
            XWPFParagraph pr = p;
            var           ms = GetMatches(p.Text);
            var           ks = new List <string>();
            var           rs = new List <string>();

            foreach (Match m in ms)
            {
                if (m.Groups.Count > 1)
                {
                    string text = m.Groups[1].Value;
                    if (text.Contains("."))
                    {
                        var ts = text.Split(".");
                        text = ts[ts.Length - 1];
                    }
                    ks.Add(text);
                    rs.Add(m.Value);
                }
            }
            bool isCt      = data.Any(op => ks.Any(o => o.Contains(op.Key)));
            bool isReplace = false;

            if (isCt)
            {
                if (ks.Count > 1)
                {
                    for (int i = 0; i < ks.Count; i++)
                    {
                        if (data.ContainsKey(ks[i]))
                        {
                            cell.SetText(data[ks[i]]?.ToString());
                            //p.
                            //p.ReplaceText(rs[i], data[ks[i]]?.ToString());
                        }
                    }
                }
                else if (ks.Count == 1)
                {
                    string text = ks[0];
                    if (data.ContainsKey(text))
                    {
                        var ct  = data[text]?.ToString();
                        var cts = ResolveText(ct);
                        var pc  = p;
                        foreach (var item2 in cts)
                        {
                            if (string.IsNullOrWhiteSpace(item2))
                            {
                                continue;
                            }
                            var pt = pc;
                            pt.ReplaceText(rs[0], item2);
                            pc = pt;
                            pr = pc;
                        }
                        isReplace = true;
                    }
                }
                if (isReplace)
                {
                    //删除原来段落
                    //p.Remove(false);
                }
            }

            return(pr);
        }
Example #12
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            //图片位置
            String       m_PicPath = @"C:\ttt.jpeg";
            FileStream   gfs       = null;
            MemoryStream ms        = new MemoryStream();
            XWPFDocument m_Docx    = new XWPFDocument();

            //页面设置
            //A4:W=11906,h=16838
            //CT_SectPr m_SectPr = m_Docx.Document.body.AddNewSectPr();
            m_Docx.Document.body.sectPr = new CT_SectPr();
            CT_SectPr m_SectPr = m_Docx.Document.body.sectPr;

            //页面设置A4纵向
            m_SectPr.pgSz.h = (ulong)16838;
            m_SectPr.pgSz.w = (ulong)11906;
            XWPFParagraph gp = m_Docx.CreateParagraph();
            // gp.GetCTPPr().AddNewJc().val = ST_Jc.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");
            gp = m_Docx.CreateParagraph();
            //gp.GetCTPPr().AddNewJc().val = ST_Jc.both;
            // gp.IndentationFirstLine = Indentation("宋体", 21, 2, FontStyle.Regular);//段首行缩进2字符
            gp.IndentationFirstLine = 15;
            gr = gp.CreateRun();
            CT_RPr   rpr    = gr.GetCTR().AddNewRPr();
            CT_Fonts rfonts = rpr.AddNewRFonts();

            rfonts.ascii    = "宋体";
            rfonts.eastAsia = "宋体";
            rpr.AddNewSz().val   = (ulong)21;//5号字体
            rpr.AddNewSzCs().val = (ulong)21;
            gr.SetText("NPOI,顾名思义,就是POI的.NET版本。那POI又是什么呢?POI是一套用Java写成的库,能够帮助开 发者在没有安装微软Office的情况下读写Office 97-2003的文件,支持的文件格式包括xls, doc, ppt等 。目前POI的稳定版本中支持Excel文件格式(xls和xlsx),其他的都属于不稳定版本(放在poi的scrachpad目录 中)。");
            //创建表
            XWPFTable table     = m_Docx.CreateTable(1, 4);              //创建一行4列表
            CT_Tbl    m_CTTbl   = m_Docx.Document.body.GetTblArray()[0]; //获得文档第一张表
            CT_TblPr  m_CTTblPr = m_CTTbl.AddNewTblPr();

            m_CTTblPr.AddNewTblW().w    = "2000";              //表宽
            m_CTTblPr.AddNewTblW().type = ST_TblWidth.dxa;
            m_CTTblPr.tblpPr               = new CT_TblPPr();  //表定位
            m_CTTblPr.tblpPr.tblpX         = "4003";           //表左上角坐标
            m_CTTblPr.tblpPr.tblpY         = "365";
            m_CTTblPr.tblpPr.tblpXSpec     = ST_XAlign.center; //若不为“Null”,则优先tblpX,即表由tblpXSpec定位
            m_CTTblPr.tblpPr.tblpYSpec     = ST_YAlign.center; //若不为“Null”,则优先tblpY,即表由tblpYSpec定位
            m_CTTblPr.tblpPr.leftFromText  = (ulong)180;
            m_CTTblPr.tblpPr.rightFromText = (ulong)180;
            m_CTTblPr.tblpPr.vertAnchor    = ST_VAnchor.text;
            m_CTTblPr.tblpPr.horzAnchor    = ST_HAnchor.page;


            //表1行4列充值:a,b,c,d
            table.GetRow(0).GetCell(0).SetText("a");
            table.GetRow(0).GetCell(1).SetText("b");
            table.GetRow(0).GetCell(2).SetText("c");
            table.GetRow(0).GetCell(3).SetText("d");
            CT_Row       m_NewRow = new CT_Row();//创建1行
            XWPFTableRow m_Row    = new XWPFTableRow(m_NewRow, table);

            table.AddRow(m_Row);                     //必须要!!!
            XWPFTableCell cell = m_Row.CreateCell(); //创建单元格,也创建了一个CT_P
            CT_Tc         cttc = cell.GetCTTc();
            CT_TcPr       ctPr = cttc.AddNewTcPr();

            //ctPr.gridSpan.val = "3";//合并3列
            cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
            cttc.GetPList()[0].AddNewR().AddNewT().Value  = "666";
            cell = m_Row.CreateCell();//创建单元格,也创建了一个CT_P
            cell.GetCTTc().GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
            cell.GetCTTc().GetPList()[0].AddNewR().AddNewT().Value  = "e";
            //合并3列,合并2行
            //1行
            m_NewRow = new CT_Row();
            m_Row    = new XWPFTableRow(m_NewRow, table);
            table.AddRow(m_Row);
            cell = m_Row.CreateCell(); //第1单元格
            cell.SetText("f");
            cell = m_Row.CreateCell(); //从第2单元格开始合并
            cttc = cell.GetCTTc();
            ctPr = cttc.AddNewTcPr();
            // ctPr.gridSpan.val = "3";//合并3列
            ctPr.AddNewVMerge().val = ST_Merge.restart;     //开始合并行
            ctPr.AddNewVAlign().val = ST_VerticalJc.center; //垂直居中
            cttc.GetPList()[0].AddNewPPr().AddNewJc().val = ST_Jc.center;
            cttc.GetPList()[0].AddNewR().AddNewT().Value  = "777";
            //2行
            m_NewRow = new CT_Row();
            m_Row    = new XWPFTableRow(m_NewRow, table);
            table.AddRow(m_Row);
            cell = m_Row.CreateCell(); //第1单元格
            cell.SetText("g");
            cell = m_Row.CreateCell(); //第2单元格
            cttc = cell.GetCTTc();
            ctPr = cttc.AddNewTcPr();
            // ctPr.gridSpan.val = "3";//合并3列
            ctPr.AddNewVMerge().val = ST_Merge.@continue;//继续合并行


            //表插入图片
            m_NewRow = new CT_Row();
            m_Row    = new XWPFTableRow(m_NewRow, table);
            table.AddRow(m_Row);
            cell = m_Row.CreateCell();//第1单元格
            //inline方式插入图片
            //gp = table.GetRow(table.Rows.Count - 1).GetCell(0).GetParagraph(table.GetRow(table.Rows.Count - 1).GetCell(0).GetCTTc().GetPList()[0]);//获得指定表单元格的段
            gp  = cell.GetParagraph(cell.GetCTTc().GetPList()[0]);
            gr  = gp.CreateRun();                                              //创建run
            gfs = new FileStream(m_PicPath, FileMode.Open, FileAccess.Read);   //读取图片文件
            gr.AddPicture(gfs, (int)PictureType.PNG, "1.jpg", 500000, 500000); //插入图片
            gfs.Close();
            //Anchor方式插入图片
            CT_Anchor an = new CT_Anchor();

            an.distB          = (uint)(0);
            an.distL          = 114300u;
            an.distR          = 114300U;
            an.distT          = 0U;
            an.relativeHeight = 251658240u;
            an.behindDoc      = false; //"0"
            an.locked         = false; //"0"
            an.layoutInCell   = true;  //"1"
            an.allowOverlap   = true;  //"1"


            NPOI.OpenXmlFormats.Dml.CT_Point2D simplePos = new NPOI.OpenXmlFormats.Dml.CT_Point2D();
            simplePos.x = (long)0;
            simplePos.y = (long)0;
            CT_EffectExtent effectExtent = new CT_EffectExtent();

            effectExtent.b = 0L;
            effectExtent.l = 0L;
            effectExtent.r = 0L;
            effectExtent.t = 0L;
            //wrapSquare(四周)
            cell = m_Row.CreateCell(); //第2单元格
            gp   = cell.GetParagraph(cell.GetCTTc().GetPList()[0]);
            gr   = gp.CreateRun();     //创建run
            CT_WrapSquare wrapSquare = new CT_WrapSquare();

            wrapSquare.wrapText = ST_WrapText.bothSides;
            gfs = new FileStream(m_PicPath, FileMode.Open, FileAccess.Read);//读取图片文件
            // gr.AddPicture(gfs, (int)PictureType.PNG, "1.png", 500000, 500000, 0, 0, wrapSquare, an, simplePos, ST_RelFromH.column, ST_RelFromV.paragraph, effectExtent);
            gr.AddPicture(gfs, (int)PictureType.PNG, "虚拟机", 500000, 500000);
            gfs.Close();
            //wrapTight(紧密)
            cell = m_Row.CreateCell(); //第3单元格
            gp   = cell.GetParagraph(cell.GetCTTc().GetPList()[0]);
            gr   = gp.CreateRun();     //创建run
            CT_WrapTight wrapTight = new CT_WrapTight();

            wrapTight.wrapText            = ST_WrapText.bothSides;
            wrapTight.wrapPolygon         = new CT_WrapPath();
            wrapTight.wrapPolygon.edited  = false;
            wrapTight.wrapPolygon.start   = new CT_Point2D();
            wrapTight.wrapPolygon.start.x = 0;
            wrapTight.wrapPolygon.start.y = 0;
            CT_Point2D lineTo = new CT_Point2D();

            wrapTight.wrapPolygon.lineTo = new List <CT_Point2D>();
            lineTo   = new CT_Point2D();
            lineTo.x = 0;
            lineTo.y = 1343;
            wrapTight.wrapPolygon.lineTo.Add(lineTo);
            lineTo   = new CT_Point2D();
            lineTo.x = 21405;
            lineTo.y = 1343;
            wrapTight.wrapPolygon.lineTo.Add(lineTo);
            lineTo   = new CT_Point2D();
            lineTo.x = 21405;
            lineTo.y = 0;
            wrapTight.wrapPolygon.lineTo.Add(lineTo);
            lineTo.x = 0;
            lineTo.y = 0;
            wrapTight.wrapPolygon.lineTo.Add(lineTo);
            gfs = new FileStream(m_PicPath, FileMode.Open, FileAccess.Read);//读取图片文件
            //gr.AddPicture(gfs, (int)PictureType.PNG, "1.png", 500000, 500000, 0, 0, wrapTight, an, simplePos, ST_RelFromH.column, ST_RelFromV.paragraph, effectExtent);
            gr.AddPicture(gfs, (int)PictureType.PNG, "虚拟机", 500000, 500000);
            gfs.Close();
            //wrapThrough(穿越)
            cell = m_Row.CreateCell();                                        //第4单元格
            gp   = cell.GetParagraph(cell.GetCTTc().GetPList()[0]);
            gr   = gp.CreateRun();                                            //创建run
            gfs  = new FileStream(m_PicPath, FileMode.Open, FileAccess.Read); //读取图片文件
            CT_WrapThrough wrapThrough = new CT_WrapThrough();

            wrapThrough.wrapText            = ST_WrapText.bothSides;
            wrapThrough.wrapPolygon         = new CT_WrapPath();
            wrapThrough.wrapPolygon.edited  = false;
            wrapThrough.wrapPolygon.start   = new CT_Point2D();
            wrapThrough.wrapPolygon.start.x = 0;
            wrapThrough.wrapPolygon.start.y = 0;
            lineTo = new CT_Point2D();
            wrapThrough.wrapPolygon.lineTo = new List <CT_Point2D>();
            lineTo   = new CT_Point2D();
            lineTo.x = 0;
            lineTo.y = 1343;
            wrapThrough.wrapPolygon.lineTo.Add(lineTo);
            lineTo   = new CT_Point2D();
            lineTo.x = 21405;
            lineTo.y = 1343;
            wrapThrough.wrapPolygon.lineTo.Add(lineTo);
            lineTo   = new CT_Point2D();
            lineTo.x = 21405;
            lineTo.y = 0;
            wrapThrough.wrapPolygon.lineTo.Add(lineTo);
            lineTo.x = 0;
            lineTo.y = 0;
            wrapThrough.wrapPolygon.lineTo.Add(lineTo);
            // gr.AddPicture(gfs, (int)PictureType.PNG, "15.png", 500000, 500000, 0, 0, wrapThrough, an, simplePos, ST_RelFromH.column, ST_RelFromV.paragraph, effectExtent);
            gr.AddPicture(gfs, (int)PictureType.PNG, "虚拟机", 500000, 500000);
            gfs.Close();


            gp = m_Docx.CreateParagraph();
            //gp.GetCTPPr().AddNewJc().val = ST_Jc.both;
            // gp.IndentationFirstLine = Indentation("宋体", 21, 2, FontStyle.Regular);//段首行缩进2字符
            gp.IndentationFirstLine = 15;
            gr = gp.CreateRun();
            gr.SetText("NPOI是POI项目的.NET版本。POI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。使用NPOI你就可以在没有安装Office或者相应环境的机器上对WORD/EXCEL文档进行读写。NPOI是构建在POI3.x版本之上的,它可以在没有安装Office的情况下对Word/Excel文档进行读写操作。");
            gp = m_Docx.CreateParagraph();
            // gp.GetCTPPr().AddNewJc().val = ST_Jc.both;
            //gp.IndentationFirstLine = Indentation("宋体", 21, 2, FontStyle.Regular);//段首行缩进2字符
            gp.IndentationFirstLine = 15;
            gr = gp.CreateRun();
            gr.SetText("NPOI之所以强大,并不是因为它支持导出Excel,而是因为它支持导入Excel,并能“理解”OLE2文档结构,这也是其他一些Excel读写库比较弱的方面。通常,读入并理解结构远比导出来得复杂,因为导入你必须假设一切情况都是可能的,而生成你只要保证满足你自己需求就可以了,如果把导入需求和生成需求比做两个集合,那么生成需求通常都是导入需求的子集。");
            //在本段中插图-wrapSquare
            //gr = gp.CreateRun();//创建run
            wrapSquare          = new CT_WrapSquare();
            wrapSquare.wrapText = ST_WrapText.bothSides;
            gfs = new FileStream(m_PicPath, FileMode.Open, FileAccess.Read);//读取图片文件
            // gr.AddPicture(gfs, (int)PictureType.PNG, "15.png", 500000, 500000, 900000, 200000, wrapSquare, an, simplePos, ST_RelFromH.column, ST_RelFromV.paragraph, effectExtent);
            gr.AddPicture(gfs, (int)PictureType.PNG, "虚拟机", 500000, 500000);
            gfs.Close();


            m_Docx.Write(ms);
            ms.Flush();
            SaveToFile(ms, Path.GetPathRoot(Directory.GetCurrentDirectory()) + "\\NPOI.docx");
        }
Example #13
0
        private void NPOITestFillData(string file)
        {
            #region 读取Word
            XWPFDocument doc;
            using (FileStream fileread = File.OpenRead(file))
            {
                doc = new XWPFDocument(fileread);
            }
            #endregion

            List <string>[] data = new List <string> [3];
            #region 组织填充数据
            List <string> a = new List <string>();
            List <string> b = new List <string>();
            List <string> c = new List <string>();
            a.Add("1.1");
            a.Add("1.2");
            a.Add("1.3");
            a.Add("1.4");
            a.Add("1.5");
            a.Add("1.6");
            a.Add("1.7");
            b.Add("2.1");
            b.Add("2.2");
            b.Add("2.3");
            b.Add("2.4");
            b.Add("2.5");
            b.Add("2.6");
            c.Add("3.1");
            c.Add("3.2");
            c.Add("3.3");
            c.Add("3.4");
            c.Add("3.5");
            c.Add("3.6");
            c.Add("3.7");
            c.Add("3.8");
            c.Add("3.9");
            data[0] = a;
            data[1] = b;
            data[2] = c;
            #endregion

            WordTable wt = new WordTable(data);

            wt.CaptionLineCount = 2;    //标题行数

            XWPFTable table = LocationTable(doc, "本年发生的非同一控制下企业合并情况");

            if (wt.ObjectData != null)
            {
                for (int i = 0; i < wt.ObjectData.Length + wt.CaptionLineCount; i++)
                {
                    if (i >= wt.CaptionLineCount)
                    {
                        XWPFTableRow row;
                        string[]     rowdata = wt.ObjectData[i - wt.CaptionLineCount].ToArray <string>();
                        if (i < table.Rows.Count)
                        {
                            row = table.GetRow(i);
                            row.GetCTRow().AddNewTrPr().AddNewTrHeight().val = 397;
                            row.GetCTRow().trPr.GetTrHeightArray(0);
                            for (int n = 0; n < rowdata.Length; n++)
                            {
                                XWPFTableCell cell = row.GetCell(n);
                                //模板中的单元格少时,接收数据将会部分丢失
                                //也可以在下边if后添加else在该行后补充单元格
                                //按接收数据循环,所以单元格数多于接收数据时不需要另做处理,该行后边的部分单元格无法补填充
                                if (cell != null)
                                {
                                    //SetText是追加内容,所以要先删除单元格内容(删除单元格内所有段落)再写入
                                    for (int p = 0; p < cell.Paragraphs.Count; p++)
                                    {
                                        cell.RemoveParagraph(p);
                                    }
                                    for (int t = 0; t < cell.Tables.Count; t++)
                                    {
                                        //表格删除
                                        //cell.RemoveTable(t);
                                    }
                                    cell.SetText(rowdata[n]);
                                }
                            }
                        }
                        else
                        {
                            //添加新行
                            //row = table.InsertNewTableRow(table.Rows.Count - 1);

                            row = new XWPFTableRow(new CT_Row(), table);
                            row.GetCTRow().AddNewTrPr().AddNewTrHeight().val = 100;
                            table.AddRow(row);

                            for (int n = 0; n < rowdata.Length; n++)
                            {
                                XWPFTableCell cell = row.CreateCell();
                                CT_Tc         tc   = cell.GetCTTc();
                                CT_TcPr       pr   = tc.AddNewTcPr();
                                tc.GetPList()[0].AddNewR().AddNewT().Value = rowdata[n];
                            }
                        }
                    }
                }
            }

            #region 保存Word
            FileStream filewrite = new FileStream(file, FileMode.Create, FileAccess.Write);
            try
            {
                doc.Write(filewrite);
            }
            catch (Exception x)
            {
                lblStatus.Text = x.Message;
            }
            finally
            {
                filewrite.Close();
            }
            #endregion
        }
Example #14
0
        public void generateWork(Invoce.Entity.Invoce invoce)
        {
            XWPFDocument doc   = new XWPFDocument();
            XWPFTable    table = doc.CreateTable(11, 1);

            table.SetLeftBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            table.SetRightBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            table.SetTopBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");


            XWPFTableCell cellFIO          = table.GetRow(0).GetCell(0);
            XWPFTableCell cellStreetBuild  = table.GetRow(1).GetCell(0);
            XWPFTableCell cellCityAndIndex = table.GetRow(2).GetCell(0);
            XWPFTableCell cellCountry      = table.GetRow(3).GetCell(0);
            XWPFTableCell cellEmail        = table.GetRow(4).GetCell(0);
            XWPFTableCell cellNumber       = table.GetRow(5).GetCell(0);
            XWPFTableCell cellDescription  = table.GetRow(6).GetCell(0);
            XWPFTableCell cellRaid         = table.GetRow(7).GetCell(0);
            XWPFTableCell cellSignature    = table.GetRow(8).GetCell(0);
            XWPFTableCell cellHelper       = table.GetRow(9).GetCell(0);
            XWPFTableCell cellFIOEnd       = table.GetRow(10).GetCell(0);



            cellFIO.SetText(invoce.GetFIO());
            cellStreetBuild.SetText(invoce.GetStreetBuild());
            cellCityAndIndex.SetText(invoce.GetCityAndIndex());
            cellCountry.SetText(invoce.GetCountry());
            cellEmail.SetText(invoce.GetEmail());
            cellNumber.SetText("+" + invoce.GetTelephoneNumber());
            cellDescription.SetText(invoce.GetDescription());
            cellRaid.SetText(invoce.GetRaid());
            cellSignature.SetText(invoce.GetSignature());
            cellHelper.SetText("Signature                          Data");
            cellFIOEnd.SetText(invoce.GetFIO());

            cellFIO.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");///Убирает нижний бордер
            cellStreetBuild.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellCityAndIndex.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellCountry.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellEmail.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellNumber.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellRaid.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellSignature.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellFIOEnd.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellDescription.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            cellHelper.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");
            XWPFParagraph p1 = cellRaid.AddParagraph();
            //XSSFCellStyle raidStyle = (HSSFCellStyle)table.CreateCellStyle();//don't use doc.CreateParagraph
            //XWPFRun r1 = p1.CreateRun();
            //cellRaid.



            //r1.SetText("This is test table contents");

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

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

            FileStream out1 = new FileStream(
                this._wordFile.GetWritePath(),
                FileMode.Create
                );

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