コード例 #1
0
        //地政函档案封面及收件回执
        public static void DZHDAFMJSJHZ(Dictionary <string, string> dic, string tplFilePath, string outputPrintFilePath)
        {
            using (FileStream tplFileStream = new FileStream(tplFilePath, FileMode.Open, FileAccess.Read))
                using (FileStream outputFileStream = File.Create(outputPrintFilePath))
                {
                    List <RespDZHSJHZ> list   = new DbHelper().QueryRespDZHSJHZ(SharpDbPrinter.Program.globalYwid);
                    XWPFDocument       tplDoc = new XWPFDocument(tplFileStream);
                    var printDoc   = DocxBaseRelace(tplDoc, dic);
                    var firstTable = printDoc.Tables[0];
                    for (int i = 0; i < list.Count; i++)
                    {
                        XWPFTableRow newRow = new XWPFTableRow(new NPOI.OpenXmlFormats.Wordprocessing.CT_Row(), firstTable);
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.MergeCells(0, 1);
                        if (list[i].MTR_NAME == null && list[i].OLD_NUM == null && list[i].DUPL_NUM == null)
                        {
                        }
                        else
                        {
                            newRow.GetCell(0).SetParagraph(SetCellText(printDoc, firstTable, list[i].MTR_NAME ?? "0"));
                            newRow.GetCell(1).SetParagraph(SetCellText(printDoc, firstTable, list[i].OLD_NUM ?? "0"));
                            newRow.GetCell(2).SetParagraph(SetCellText(printDoc, firstTable, list[i].DUPL_NUM ?? "0"));
                        }

                        firstTable.AddRow(newRow, 2 + i);
                    }
                    firstTable.RemoveRow(1);

                    printDoc.Write(outputFileStream);
                }
        }
コード例 #2
0
ファイル: Program.cs プロジェクト: nissl-lab/npoi-examples
        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);
            }
        }
コード例 #3
0
        /// <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");
            }
        }
コード例 #4
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));
            }
        }
コード例 #5
0
        // 给一个table , 追加行
        private static void UpdateTable(XWPFTable table)
        {
            //创建表格-提前创建好表格后填数
            //      XWPFTable tableContent = doc.Tables[0];//4行5列

            for (int i = 0; i < 10; i++)
            {
                XWPFTableRow row = table.CreateRow();
                row.GetCell(0).SetText("name");
                row.GetCell(1).SetText("age");
                row.GetCell(2).SetText("sex");
                row.GetCell(3).SetText("mark");
            }

            // tableContent.AddNewCol();
            // tableContent.AddNewCol();
            // tableContent.AddNewCol();
            // tableContent.AddNewCol();


            // tableContent.CreateRow();
            // tableContent.CreateRow();
            // tableContent.CreateRow();
            // tableContent.CreateRow();
            // tableContent.CreateRow();

            // // tableContent.Width = 1000 * 5;
            // // tableContent.SetColumnWidth(0, 1000);/* 设置列宽 */
            // // tableContent.SetColumnWidth(1, 1500);
            // // tableContent.SetColumnWidth(2, 1500);
            // // tableContent.SetColumnWidth(3, 1000);

            // tableContent.GetRow(0).GetCell(0).SetParagraph(SetCellText(doc, tableContent, "地点"));
            // tableContent.GetRow(0).GetCell(1).SetParagraph(SetCellText(doc, tableContent, "日期"));
            // tableContent.GetRow(0).GetCell(2).SetParagraph(SetCellText(doc, tableContent, "男性"));
            // tableContent.GetRow(0).GetCell(3).SetParagraph(SetCellText(doc, tableContent, "女性"));
            // tableContent.GetRow(0).GetCell(4).SetParagraph(SetCellText(doc, tableContent, "合计"));

            // //测试数据格式
            // List<ArrayList> list = new List<ArrayList>()
            // {
            //     new ArrayList(){ "航天桥", "-", "0", "0", "0"},
            //     new ArrayList(){ "马甸", "-", "0", "0", "0" },
            //     new ArrayList(){"洋桥", "04月16日 - 05月31日", "0", "0", "0"},

            // };
            // for (int i = 0; i < list.Count; i++)//有3个数组
            // {
            //     ArrayList ls = list[i];
            //     for (int j = 0; j < ls.Count; j++)
            //     {
            //         tableContent.GetRow(i + 1).GetCell(j).SetParagraph(SetCellText(doc, tableContent, ls[j].ToString()));
            //     }
            // }
        }
コード例 #6
0
        private XWPFDocument InsertTable(XWPFDocument doc, Table t)
        {
            var maxColCount = t.Rows.Max(x => x.Cells.Count);

            if (t == null)
            {
                return(doc);
            }

            var table = doc.CreateTable();

            table.Width = t.Width;

            int index = 0;

            t.Rows?.ForEach(r =>
            {
                XWPFTableRow tableRow = index == 0 ? table.GetRow(0) : table.CreateRow();

                for (int i = 0; i < r.Cells.Count; i++)
                {
                    var cell     = r.Cells[i];
                    var xwpfCell = i == 0 ? tableRow.GetCell(0) : tableRow.AddNewTableCell();
                    foreach (var para in cell.Paragraphs)
                    {
                        xwpfCell.AddParagraph().Set(para);
                    }

                    if (!string.IsNullOrWhiteSpace(cell.Color))
                    {
                        tableRow.GetCell(i).SetColor(cell.Color);
                    }
                }

                //补全单元格,并合并
                var rowColsCount = tableRow.GetTableICells().Count;
                if (rowColsCount < maxColCount)
                {
                    for (int i = rowColsCount - 1; i < maxColCount; i++)
                    {
                        tableRow.CreateCell();
                    }
                    tableRow.MergeCells(rowColsCount - 1, maxColCount);
                }

                index++;
            });

            return(doc);
        }
コード例 #7
0
ファイル: WordHelper.cs プロジェクト: cfires/Cfires.Tutor
        private static void AddTableData <T>(XWPFDocument doc, IEnumerable <T> tableSource) where T : class, new()
        {
            XWPFTable tableAdd = doc.Tables[0];

            T obj = new T();

            PropertyInfo[] properties = obj.GetType().GetProperties().ToArray();

            int colSize = tableAdd.GetRow(0).GetTableCells().Count;

            if (colSize != properties.Length)
            {
                throw new ArgumentException("对象属性数量与表格列数量不一致");
            }

            foreach (T t in tableSource)
            {
                XWPFTableRow row = tableAdd.CreateRow();
                for (int i = 0; i < properties.Length; i++)
                {
                    object valObj = properties[i].GetValue(t);
                    row.GetCell(i).SetText(valObj == null ? string.Empty : valObj.ToString());
                }
            }
        }
コード例 #8
0
ファイル: WordManager.cs プロジェクト: yyt2019/Materal
        /// <summary>
        /// 应用表格模板
        /// </summary>
        /// <param name="tableContent"></param>
        /// <param name="tableTemplate"></param>
        /// <param name="colNames"></param>
        private void ApplyToTableTemplate(XWPFTable tableContent, TableTemplateModel tableTemplate, Dictionary <int, string> colNames)
        {
            int startRowNum = tableTemplate.StartRowNumber;

            for (var rowIndex = 0; rowIndex < tableTemplate.Value.Rows.Count; rowIndex++)
            {
                int          documentRowIndex = rowIndex + startRowNum;
                XWPFTableRow row       = rowIndex == 0 ? tableContent.GetRow(documentRowIndex) : tableContent.InsertNewTableRow(documentRowIndex - 1);
                int          cellCount = row.GetTableCells().Count;
                int          count     = colNames.Max(m => m.Key);
                for (int i = cellCount - 1; i < count; i++)
                {
                    row.CreateCell();
                }
                foreach (KeyValuePair <int, string> colName in colNames)
                {
                    string[]      colValues = colName.Value.Split(',');
                    string        value     = tableTemplate.Value.Rows[rowIndex][colValues[0]].ToString();
                    XWPFParagraph paragraph = GetCellContent(rowIndex, colName.Key, tableContent, value, tableTemplate.OnSetCellText);
                    XWPFTableCell cell      = row.GetCell(colName.Key);
                    cell.SetParagraph(paragraph);
                    for (var i = 1; i < colValues.Length; i++)
                    {
                        ApplyCommand(colValues[i], colName.Key, row);
                    }
                }
            }
        }
コード例 #9
0
        public void TestSetGetVertAlignment()
        {
            // instantiate the following classes so they'll Get picked up by
            // the XmlBean process and Added to the jar file. they are required
            // for the following XWPFTableCell methods.
            CT_Shd ctShd = new CT_Shd();

            Assert.IsNotNull(ctShd);
            CT_VerticalJc ctVjc = new CT_VerticalJc();

            Assert.IsNotNull(ctVjc);
            ST_Shd stShd = ST_Shd.nil;

            Assert.IsNotNull(stShd);
            ST_VerticalJc stVjc = ST_VerticalJc.top;

            Assert.IsNotNull(stVjc);

            // create a table
            XWPFDocument doc     = new XWPFDocument();
            CT_Tbl       ctTable = new CT_Tbl();
            XWPFTable    table   = new XWPFTable(ctTable, doc);
            // table has a single row by default; grab it
            XWPFTableRow tr = table.GetRow(0);

            Assert.IsNotNull(tr);
            // row has a single cell by default; grab it
            XWPFTableCell cell = tr.GetCell(0);

            cell.SetVerticalAlignment(XWPFTableCell.XWPFVertAlign.BOTH);
            XWPFTableCell.XWPFVertAlign al = cell.GetVerticalAlignment().Value;
            Assert.AreEqual(XWPFTableCell.XWPFVertAlign.BOTH, al);
        }
コード例 #10
0
 private string GetReference(XWPFTableRow row)
 {
     try
     {
         return(row.GetCell(3).Paragraphs[0].Runs[0].Text);
     }
     catch
     {
         return(null);
     }
 }
コード例 #11
0
ファイル: WordExport.cs プロジェクト: AlbertAY/PlayAndStudy
        /// <summary>
        /// 获取表头的名称
        /// </summary>
        /// <param name="table"></param>
        /// <param name="tableName"></param>
        /// <returns></returns>
        public Dictionary <int, string> GetTableField(XWPFTableRow row, string tableName, List <Field> fieldList)
        {
            Dictionary <int, string> tableField = new Dictionary <int, string>();

            for (int j = 0; j < row.GetTableCells().Count; j++)
            {
                string text = row.GetCell(j).GetText();
                if (text.Contains(tableName))
                {
                    tableField.Add(j, text);
                    Field field = fieldList.FirstOrDefault(it => it.SignName == text);
                    if (field != null)
                    {
                        //移除第一行数据
                        row.GetCell(j).RemoveParagraph(0);
                        row.GetCell(j).SetText(field.Name);
                    }
                }
            }
            return(tableField);
        }
コード例 #12
0
ファイル: OrderController.cs プロジェクト: nygula/WebApi
        /// <summary>
        /// 复制行
        /// </summary>
        /// <param name="targetRow"></param>
        /// <param name="sourceRow"></param>
        private void XWPFTableRowCopy(XWPFTableRow targetRow, XWPFTableRow sourceRow)
        {
            targetRow.GetCTRow().trPr     = sourceRow.GetCTRow().trPr;
            List <XWPFTableCell> cellList = sourceRow.GetTableCells();

            //复制列及其属性和内容
            foreach (var sourceCell in cellList)
            {
                var index      = cellList.IndexOf(sourceCell);
                var targetCell = targetRow.GetCell(index);
                if (targetCell == null)
                {
                    break;
                }
                targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr;
                if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0)
                {
                    //设置段落样式
                    var sourceParagraph = sourceCell.Paragraphs[0];
                    targetCell.Paragraphs[0].Alignment = ParagraphAlignment.CENTER;
                    if (sourceParagraph.Runs != null && sourceParagraph.Runs.Count > 0)
                    {
                        var cellR = targetCell.Paragraphs[0].CreateRun();
                        cellR.SetText(sourceCell.GetText());
                        cellR.IsBold = sourceParagraph.Runs[0].IsBold;
                        //cellR.FontFamily = sourceParagraph.Runs[0].FontFamily;
                        cellR.FontSize = 10;
                    }
                    else
                    {
                        targetRow.GetCell(index).SetText(sourceCell.GetText());
                    }
                }
                else
                {
                    targetRow.GetCell(index).SetText(sourceCell.GetText());
                }
            }
        }
コード例 #13
0
        //地政函审批表(改功能)
        /// <summary>
        /// 将模板文档的源关键字替换成目标文本
        /// </summary>
        /// <param name="dic">基础替换文本字典</param>
        /// <param name="formatParaDic">包含换行符的替换目标字典</param>
        /// <param name="tplFilePath">模板文件的路径</param>
        /// <param name="outputPrintFilePath">输出文件路径</param>
        public static void DZHSPBGGN(Dictionary <string, string> dic, Dictionary <string, string> formatParaDic, string tplFilePath, string outputPrintFilePath)
        {
            using (FileStream tplFileStream = new FileStream(tplFilePath, FileMode.Open, FileAccess.Read))
                using (FileStream outputFileStream = File.Create(outputPrintFilePath))
                {
                    List <RespDZHSPBChild> list   = new DbHelper().QueryDZHSPB1_Child(SharpDbPrinter.Program.globalYwid);
                    XWPFDocument           tplDoc = new XWPFDocument(tplFileStream);
                    var printDoc = DocxRepalceWithParaFormat(tplDoc, formatParaDic);
                    printDoc = DocxBaseRelace(printDoc, dic);
                    int row1       = 9;
                    var firstTable = printDoc.Tables[0];
                    for (int i = 0; i < list.Count; i++)
                    {
                        XWPFTableRow newRow = new XWPFTableRow(new NPOI.OpenXmlFormats.Wordprocessing.CT_Row(), firstTable);
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.CreateCell();
                        newRow.MergeCells(5, 9);
                        newRow.MergeCells(0, 4);
                        newRow.GetCell(0).SetParagraph(SetCellText(printDoc, firstTable, list[i].th ?? ""));
                        newRow.GetCell(1).SetParagraph(SetCellText(printDoc, firstTable, list[i].YTDSYZH ?? ""));
                        newRow.GetCell(2).SetParagraph(SetCellText(printDoc, firstTable, list[i].PZMJ ?? ""));
                        firstTable.AddRow(newRow, row1 + 1 + i);
                    }
                    firstTable.RemoveRow(row1);

                    printDoc.Write(outputFileStream);
                }
        }
コード例 #14
0
        public static XWPFTableCell GetCell(XWPFTableRow row, int line, XWPFTableRow modelRow)
        {
            XWPFTableCell cell = row.GetCell(line);

            if (cell == null)
            {
                cell = row.CreateCell();
                if (modelRow != null)
                {
                    var modelcell = modelRow.GetCell(line);
                    cell.SetVerticalAlignment(modelcell.GetVerticalAlignment());
                    cell.SetColor(modelcell.GetColor());
                }
            }
            return(cell);
        }
コード例 #15
0
        public void Test54099()
        {
            XWPFDocument  doc     = new XWPFDocument();
            CT_Tbl        ctTable = new CT_Tbl();
            XWPFTable     table   = new XWPFTable(ctTable, doc);
            XWPFTableRow  tr      = table.GetRow(0);
            XWPFTableCell cell    = tr.GetCell(0);

            CT_Tc     ctTc   = cell.GetCTTc();
            CT_TcPr   tcPr   = ctTc.AddNewTcPr();
            CT_HMerge hMerge = tcPr.AddNewHMerge();

            hMerge.val = (ST_Merge.restart);

            CT_TcBorders tblBorders = tcPr.AddNewTcBorders();
            CT_VMerge    vMerge     = tcPr.AddNewVMerge();
        }
コード例 #16
0
        public void TestSetGetColor()
        {
            // create a table
            XWPFDocument doc     = new XWPFDocument();
            CT_Tbl       ctTable = new CT_Tbl();
            XWPFTable    table   = new XWPFTable(ctTable, doc);
            // table has a single row by default; grab it
            XWPFTableRow tr = table.GetRow(0);

            Assert.IsNotNull(tr);
            // row has a single cell by default; grab it
            XWPFTableCell cell = tr.GetCell(0);

            cell.SetColor("F0000F");
            String clr = cell.GetColor();

            Assert.AreEqual("F0000F", clr);
        }
コード例 #17
0
        /// <summary>
        /// Fill table row with data
        /// </summary>
        /// <param name="row">Row to write into.</param>
        /// <param name="cellData">Cell data to write into the row.</param>
        /// <returns>The row which the data has been written into.</returns>
        public static XWPFTableRow FillRow <T>(this XWPFTableRow row, IEnumerable <T> cellData)
        {
            if (row == null)
            {
                throw new ArgumentNullException(nameof(row));
            }

            int ii = 0;

            foreach (var val in cellData)
            {
                var cell = row.GetCell(ii) ?? row.AddNewTableCell();
                cell.SetText(Convert.ToString(val));

                ii++;
            }

            return(row);
        }
コード例 #18
0
ファイル: WordExport.cs プロジェクト: AlbertAY/PlayAndStudy
        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());
                        }
                    }
                }
            }
        }
コード例 #19
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);
            }
        }
コード例 #20
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);
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// 处理表格
        /// </summary>
        /// <param name="tableCell"></param>
        /// <param name="list"></param>
        private void ProcessTableCell(TableCell tableCell, IEnumerable <DynamicEntity> list)
        {
            var newList = list.ToList();

            list = list.ToList();
            //if (tableCell.Paragraph.Runs.Count != 1) return;
            //Regex reg = new Regex(matchDouble, RegexOptions.Multiline | RegexOptions.Singleline);
            //MatchCollection matchs = reg.Matches(tableCell.Paragraph.ParagraphText);
            //if (matchs == null || matchs.Count != 1) return;
            //string propertyName = Regex.Replace(matchs[0].Value, repDouble, "");
            string propertyName = Regex.Replace(tableCell.Paragraph.Text, repDouble, "");
            var    runs         = tableCell.Paragraph.Runs.Where(t => t.Text.Contains(propertyName.Trim()));

            if (runs == null || runs.Any() == false)
            {
                return;
            }
            var    run      = runs.FirstOrDefault();
            int    index    = tableCell.Paragraph.Runs.IndexOf(run);
            CT_RPr oldStyle = tableCell.Paragraph.Runs[index].GetCTR().rPr;

            DealSurlusRun(tableCell.Paragraph, run, validDouble);
            index = tableCell.Paragraph.Runs.IndexOf(run);
            //int num = 0;
            //if (index >= 1)
            //{
            //    var frontRun = tableCell.Paragraph.Runs[index - 1];
            //    if (frontRun.Text.Contains(validDouble))
            //    {
            //        tableCell.Paragraph.RemoveRun(index - 1);
            //        num += 1;
            //    }
            //}
            //var afterRun = tableCell.Paragraph.Runs[index + 1 - num];
            //if (afterRun.Text.TrimStart().StartsWith("}"))
            //{
            //    tableCell.Paragraph.RemoveRun(index + 1 - num);
            //}
            int rowIndex = tableCell.RowIndex;
            var rowPr    = tableCell.Table.GetRow(tableCell.RowIndex).GetCTRow().trPr;
            var cellPr   = tableCell.Cell.GetCTTc().tcPr;

            for (var i = 0; i < list.Count(); i++)
            {
                DynamicEntity entity = newList[i];
                //if (entity.IsEntityProperty(propertyName.Trim()) == false) continue;
                object value = entity.GetPropertyValue(propertyName.Trim(), false);
                if (value == null)
                {
                    value = string.Empty;
                }
                if (i == 0)
                {
                    tableCell.Paragraph.RemoveRun(index);
                    XWPFRun newRun = tableCell.Paragraph.CreateRun();
                    if (value != null)
                    {
                        if (value is byte[])
                        {
                            byte[] bytes = value as byte[];
                            using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
                            {
                                newRun.AddPicture(ms, (int)PictureType.PNG, "test.png", NPOI.Util.Units.ToEMU(100), NPOI.Util.Units.ToEMU(100));
                                ms.Close();
                            }
                        }
                        else
                        {
                            newRun.SetText(value.ToString());
                        }
                    }
                    rowIndex += 1;
                    continue;
                }
                XWPFTableRow row = tableCell.Table.GetRow(rowIndex);
                if (row == null)
                {
                    row = tableCell.Table.CreateRow();
                    row.GetCTRow().trPr = rowPr;
                }
                XWPFTableCell cell  = row.GetCell(tableCell.CellIndex);
                var           cells = row.GetTableCells();
                if (cells != null && cells.Count == 1)
                {
                    string       sdasd     = string.Empty;
                    XWPFTableRow newRow    = tableCell.Table.CreateRow();
                    newRow.GetCTRow().trPr = rowPr;
                    tableCell.Table.AddRow(newRow, rowIndex);
                    tableCell.Table.RemoveRow(rowIndex + 2);
                    cell = newRow.GetCell(tableCell.CellIndex);
                    newRow.GetCell(0).SetText(rowIndex.ToString());
                    newRow.GetCell(0).GetCTTc().AddNewTcPr();
                    newRow.GetCell(0).GetCTTc().tcPr = cellPr;
                }
                if (cell == null)
                {
                    continue;
                }
                if (value != null)
                {
                    //cell.SetText(value.ToString());
                    if (cell.Paragraphs == null || cell.Paragraphs.Count == 0)
                    {
                        cell.AddParagraph();
                    }
                    cell.Paragraphs[0].RemoveRun(0);
                    XWPFRun newRun = cell.Paragraphs[0].CreateRun();
                    if (value is byte[])
                    {
                        byte[] bytes = value as byte[];
                        using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
                        {
                            newRun.AddPicture(ms, (int)PictureType.PNG, "test.png", NPOI.Util.Units.ToEMU(100), NPOI.Util.Units.ToEMU(100));
                            ms.Close();
                        }
                    }
                    else
                    {
                        newRun.SetText(value.ToString());
                    }
                    newRun.GetCTR().rPr = oldStyle;
                    //XWPFRun newRun = cell.AddParagraph().CreateRun();
                    //newRun.SetText(value.ToString());
                    //newRun.GetCTR().rPr = oldStyle;
                }
                cell.GetCTTc().AddNewTcPr();
                cell.GetCTTc().tcPr = cellPr;
                rowIndex += 1;
            }
        }
コード例 #22
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();
            }
        }
コード例 #23
0
ファイル: WordExport.cs プロジェクト: AlbertAY/PlayAndStudy
        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());
                        }
                    }
                }
            }
        }
コード例 #24
0
ファイル: NPOIHelper.cs プロジェクト: zinda2000/EasyOffice
        /// <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
                {
                }
            }
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: ilaipi/read-word-table
        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);
        }