コード例 #1
0
        /// <summary>
        /// 为XWPFDocument文档复制指定索引的表
        /// </summary>
        /// <param name="readDoc">模板文件</param>
        /// <param name="tableIndex">需要复制模板的table的索引</param>
        /// <param name="targetIndex">复制到目标位置的table索引(如果目标位置原来有表格,会被覆盖)</param>
        /// <param name="myDoc">新创建的文件</param>
        public static void CopyTable(XWPFDocument readDoc, int tableIndex, int targetIndex, XWPFDocument myDoc)
        {
            var    sourceTable = readDoc.Tables[tableIndex];
            CT_Tbl sourceCTTbl = readDoc.Document.body.GetTblArray(8);

            var targetTable = myDoc.CreateTable();

            myDoc.SetTable(targetIndex, targetTable);
            var targetCTTbl = myDoc.Document.body.GetTblArray()[myDoc.Document.body.GetTblArray().Length - 1];

            targetCTTbl.tblPr        = sourceCTTbl.tblPr;
            targetCTTbl.tblPr.jc.val = ST_Jc.left;//表格在页面水平位置
            //targetCTTbl.tblGrid = sourceCTTbl.tblGrid;

            for (int i = 0; i < sourceTable.Rows.Count; i++)
            {
                var tbRow     = targetTable.CreateRow();
                var targetRow = tbRow.GetCTRow();
                tbRow.RemoveCell(0);
                XWPFTableRow row = sourceTable.Rows[i];
                targetRow.trPr = row.GetCTRow().trPr;
                for (int c = 0; c < row.GetTableCells().Count; c++)
                {
                    var tbCell = tbRow.CreateCell();
                    tbCell.RemoveParagraph(0);
                    var targetCell = tbCell.GetCTTc();

                    XWPFTableCell cell = row.GetTableCells()[c];
                    targetCell.tcPr = cell.GetCTTc().tcPr;
                    for (int p = 0; p < cell.Paragraphs.Count; p++)
                    {
                        var           tbPhs     = tbCell.AddParagraph();
                        CT_P          targetPhs = tbPhs.GetCTP();
                        XWPFParagraph para      = cell.Paragraphs[p];
                        var           paraCTP   = para.GetCTP();
                        targetPhs.pPr          = paraCTP.pPr;
                        targetPhs.rsidR        = paraCTP.rsidR;
                        targetPhs.rsidRPr      = paraCTP.rsidRPr;
                        targetPhs.rsidRDefault = paraCTP.rsidRDefault;
                        targetPhs.rsidP        = paraCTP.rsidP;

                        for (int r = 0; r < para.Runs.Count; r++)
                        {
                            var  tbRun     = tbPhs.CreateRun();
                            CT_R targetRun = tbRun.GetCTR();

                            XWPFRun run    = para.Runs[r];
                            var     runCTR = run.GetCTR();
                            targetRun.rPr     = runCTR.rPr;
                            targetRun.rsidRPr = runCTR.rsidRPr;
                            targetRun.rsidR   = runCTR.rsidR;
                            CT_Text text = targetRun.AddNewT();
                            text.Value = run.Text;
                        }
                    }
                }
            }
            targetTable.RemoveRow(0);
        }
コード例 #2
0
ファイル: CaseWord.cs プロジェクト: Z-K-P/SimpleTest
        public void Read()
        {
            FileStream   stream = new FileStream(filename, FileMode.Open);
            XWPFDocument doc    = new XWPFDocument(stream);

            //解析段落
            foreach (XWPFParagraph para in doc.Paragraphs)
            {
                string text = para.ParagraphText;
                Console.WriteLine(text);
                //另一种方式
                //foreach (XWPFRun run in para.Runs)
                //{
                //    text = run.ToString();
                //    Console.Write(text+"text");
                //}
            }

            //解析表格
            XWPFTable table = doc.Tables[0];

            for (int row = 1; row < table.Rows.Count; row++)
            {
                XWPFTableRow r = table.Rows[row];
                foreach (XWPFTableCell cell in r.GetTableCells())
                {
                    string str = cell.GetText();
                    Console.Write(str + "\t");
                }
                Console.WriteLine();
            }
            Console.Read();
        }
コード例 #3
0
        public static void JTClearRuns(this XWPFTableRow row)
        {
            var cells = row.GetTableCells();
            var count = cells.Count;

            for (int i = 0; i < count; i++)
            {
                var cell       = cells[i];
                var paragraphs = cell.Paragraphs;
                if (paragraphs == null)
                {
                    throw new JTNoParagraphExistInCellException();
                }
                var pCount = paragraphs.Count;
                for (int j = 0; j < pCount; j++)
                {
                    var paragraph = paragraphs[j];
                    var runs      = paragraph.Runs;
                    if (runs != null)
                    {
                        var rCount = runs.Count;
                        for (int k = 0; k < rCount; k++)
                        {
                            paragraph.RemoveRun(0);
                        }
                    }
                }
            }
        }
コード例 #4
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);
                    }
                }
            }
        }
コード例 #5
0
        /// <summary>
        /// 获取表中的列信息
        /// </summary>
        /// <param name="row">行节点</param>
        /// <param name="dic">列名字典集合</param>
        /// <param name="pTable">表信息</param>
        private void InitColumns(XWPFTableRow row, Dictionary <int, string> dic, TableInfo pTable)
        {
            ColumnInfo mColumn = new ColumnInfo();
            int        iCell   = 0;

            //列ID
            mColumn.ColumnObjectId = Guid.NewGuid().ToString();
            string sTemp = "";

            foreach (var cell in row.GetTableCells())
            {
                sTemp = cell.GetText().Trim();
                Common.GetColumnInfo(dic, sTemp, mColumn, iCell, pTable);
                iCell++;
            }
            mColumn.DataTypeStr = Common.GetDataTypeStr(mColumn.DataTypeStr, mColumn.Width);
            mColumn.Width       = Common.GetColumnWidth(mColumn.DataTypeStr);

            if (string.IsNullOrEmpty(mColumn.Comment))
            {
                mColumn.Comment = mColumn.Name;
            }
            if (string.IsNullOrEmpty(mColumn.DefaultValue))
            {
                mColumn.DefaultValue = "";
            }
            mColumn.Sequence = pTable.ListColumnInfo.Count + 1;
            pTable.ListColumnInfo.Add(mColumn);
        }
コード例 #6
0
ファイル: NPOIWordHelper.cs プロジェクト: ywscr/EasyNPOI
 /// <summary>
 /// 替换表格中的一行
 /// </summary>
 /// <param name="addedRow"></param>
 /// <param name="dataRow"></param>
 private static void ReplaceRow(XWPFTableRow addedRow, Models.Word.ReplacementRow dataRow)
 {
     //遍历新行的每个单元格,进行赋值
     foreach (var cell in addedRow.GetTableCells())
     {
         ReplaceInParagraphs(cell.Paragraphs, dataRow.Cells);
     }
 }
コード例 #7
0
ファイル: NpoiHeplper.cs プロジェクト: raikay/Demo
 private static void ReplaceRow(XWPFTableRow row, Dictionary <string, object> data)
 {
     foreach (var cell in row.GetTableCells())
     {
         foreach (var item in cell.Paragraphs)
         {
             ReplaceParagraph(item, data, cell);
         }
     }
 }
コード例 #8
0
        /// <summary>
        /// 设置表格行背景
        /// </summary>
        /// <param name="row"></param>
        /// <param name="strRGB"></param>
        /// <returns></returns>
        public static XWPFTableRow SetRowBackgroundColor(this XWPFTableRow row, string strRGB)
        {
            var cells = row.GetTableCells();

            foreach (var c in cells)
            {
                c.SetColor(strRGB);
            }
            return(row);
        }
コード例 #9
0
ファイル: OrderController.cs プロジェクト: nygula/WebApi
        /// <summary>
        /// 替换订单item标签
        /// </summary>
        /// <param name="row"></param>
        /// <param name="item"></param>
        /// <param name="index"></param>
        private void ReplaceItemKey(XWPFTableRow row, CrmOrderItemEntity item, int index)
        {
            foreach (var cell in row.GetTableCells())
            {
                var text = cell.GetText();
                switch (text)
                {
                case "{index}":
                    text = text.Replace(text, index.ToString());
                    break;

                case "{productId}":
                    text = text.Replace(text, item.ProductId.GetHashCode().ToString());
                    break;

                case "{productFullName}":
                    text = text.Replace(text, item.ProductFullName);
                    break;

                case "{unit}":
                    text = text.Replace(text, "PCS");
                    break;

                case "{count}":
                    text = text.Replace(text, item.Count.ToString());
                    break;

                case "{singlePrice}":
                    text = text.Replace(text, item.SinglePrice.ToString("N2"));
                    break;

                case "{totalPrice}":
                    text = text.Replace(text, item.TotalPrice.ToString("N2"));
                    break;

                case "{remark}":
                    text = text.Replace(text, "");
                    break;
                }

                // 为保留模板的格式
                foreach (var para in cell.Paragraphs)
                {
                    for (var i = 0; i < para.Runs.Count; i++)
                    {
                        para.Runs[i].SetText(i == para.Runs.Count - 1 ? text : "", 0);
                    }
                }
            }
        }
コード例 #10
0
ファイル: WordGenerator.cs プロジェクト: radtek/EMIP
        private static void CopyRow(XWPFTableRow templateRow, XWPFTableRow row)
        {
            if (row.Height != templateRow.Height)
            {
                row.Height = templateRow.Height;
            }

            List <XWPFTableCell> templateCells = templateRow.GetTableCells();

            foreach (XWPFTableCell templateCell in templateCells)
            {
                XWPFTableCell cell = row.CreateCell();
                WordGenerator.CopyCell(templateCell, cell);
            }
        }
コード例 #11
0
        /// <summary>
        /// 设置行文本
        /// </summary>
        /// <param name="row"></param>
        /// <param name="textArray"></param>
        /// <returns></returns>
        public static XWPFTableRow SetRowText(this XWPFTableRow row, params string[] textArray)
        {
            var cells = row.GetTableCells();
            int index = 0;

            foreach (var c in cells)
            {
                if (index < textArray.Length && textArray[index] != null)
                {
                    c.SetText(textArray[index]);
                    index++;
                }
            }
            return(row);
        }
コード例 #12
0
ファイル: OrderController.cs プロジェクト: nygula/WebApi
        /// <summary>
        /// 替换订单标签
        /// </summary>
        /// <param name="row"></param>
        /// <param name="item"></param>
        /// <param name="index"></param>
        private void ReplaceOrderKey(XWPFTableRow row, CrmOrderEntity item, int index)
        {
            foreach (var cell in row.GetTableCells())
            {
                var text = cell.GetText().Trim();
                switch (text)
                {
                case "金额合计(大写):{allTotalPriceBig}":
                    text = text.Replace("{allTotalPriceBig}", item.TotlaPrice.ToString("N2").MoneyToChinese());
                    break;

                case "小写金额:{allTotalPriceSmall}":
                    text = text.Replace("{allTotalPriceSmall}", item.TotlaPrice.ToString("N2"));
                    break;

                case "{index}":
                    text = text.Replace(text, index.ToString());
                    break;

                case "{productId}":
                    text = text.Replace(text, "运费");
                    break;

                case "{totalPrice}":
                    text = text.Replace(text, item.FreightPrice.ToString("N2"));
                    break;

                case "{productFullName}":
                case "{unit}":
                case "{count}":
                case "{singlePrice}":
                case "{remark}":
                    text = text.Replace(text, "");
                    break;
                }

                // 为保留模板的格式
                foreach (var para in cell.Paragraphs)
                {
                    for (var i = 0; i < para.Runs.Count; i++)
                    {
                        para.Runs[i].SetText(i == para.Runs.Count - 1 ? text : "", 0);
                    }
                }
            }
        }
コード例 #13
0
ファイル: WordGenerator.cs プロジェクト: radtek/EMIP
        private static MergeField GetFirstArrayMergeField(XWPFTableRow row)
        {
            foreach (XWPFTableCell cell in row.GetTableCells())
            {
                foreach (XWPFParagraph ph in cell.Paragraphs)
                {
                    foreach (XWPFRun run in ph.Runs)
                    {
                        MergeField mergeField = WordGenerator.ParesMergeField(run);
                        if (mergeField != null && mergeField.isArray)
                        {
                            return(mergeField);
                        }
                    }
                }
            }

            return(null);
        }
コード例 #14
0
ファイル: WordManager.cs プロジェクト: yyt2019/Materal
        /// <summary>
        /// 应用命令
        /// </summary>
        /// <param name="command"></param>
        /// <param name="colIndex"></param>
        /// <param name="row"></param>
        private void ApplyCommand(string command, int colIndex, XWPFTableRow row)
        {
            string[] commands = command.Split(':');
            if (commands.Length != 2)
            {
                return;
            }
            string type      = commands[0];
            string typeValue = commands[1];

            if (type == "RowSpan")
            {
                int endColIndex = colIndex + typeValue.ConvertTo <int>() - 1;
                int cellCount   = row.GetTableCells().Count;
                for (int j = cellCount; j <= endColIndex; j++)
                {
                    row.CreateCell();
                }
                row.MergeCells(colIndex, endColIndex);
            }
        }
コード例 #15
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);
        }
コード例 #16
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());
                }
            }
        }
コード例 #17
0
ファイル: WordGenerator.cs プロジェクト: radtek/EMIP
 private static void FillGrid(XWPFTable doctable, GridDefine gridDefine, DataTable table)
 {
     for (int i = 0; i < table.Rows.Count; i++)
     {
         DataRow      row    = table.Rows[i];
         XWPFTableRow docrow = doctable.GetRow(gridDefine.StartRowIndex + i);
         foreach (XWPFTableCell cell in docrow.GetTableCells())
         {
             foreach (XWPFParagraph ph in cell.Paragraphs)
             {
                 foreach (XWPFRun run in ph.Runs)
                 {
                     MergeField field = WordGenerator.ParesMergeField(run);
                     if (field != null && table.Columns.Contains(field.ColumnName))
                     {
                         WordGenerator.Fill(run, field, row[field.ColumnName], 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
ファイル: WordManager.cs プロジェクト: yyt2019/Materal
        /// <summary>
        /// 获得表名和列表
        /// </summary>
        /// <param name="tableContent"></param>
        /// <param name="rowIndex"></param>
        /// <returns></returns>
        private (string tableName, Dictionary <int, string> colNames) GetTableNameAndColName(XWPFTable tableContent, int rowIndex)
        {
            XWPFTableRow         row   = tableContent.GetRow(rowIndex);
            List <XWPFTableCell> cells = row.GetTableCells();

            if (cells.Count <= 0 || cells[0].BodyElements.Count <= 0)
            {
                return(null, null);
            }
            string tableName = string.Empty;
            var    colNames  = new Dictionary <int, string>();

            for (var index = 0; index < cells.Count; index++)
            {
                IBodyElement bodyElement = cells[index].BodyElements[0];
                if (!(bodyElement is XWPFParagraph paragraph))
                {
                    continue;
                }
                string value = paragraph.ParagraphText;
                if (!value.VerifyRegex("^{\\$.+\\..+\\}$"))
                {
                    continue;
                }
                string[] tableNameAndColumnName = value.Substring(2, value.Length - 3).Split('.');
                if (tableNameAndColumnName.Length != 2)
                {
                    continue;
                }
                tableName = tableNameAndColumnName[0];
                if (colNames.ContainsKey(index))
                {
                    continue;
                }
                colNames.Add(index, tableNameAndColumnName[1]);
            }

            return(tableName, colNames);
        }
コード例 #20
0
ファイル: OrderController.cs プロジェクト: nygula/WebApi
        /// <summary>
        /// 替换公司和客户标签
        /// </summary>
        /// <param name="row"></param>
        /// <param name="item"></param>
        /// <param name="client"></param>
        private void ReplaceClientCompanyKey(XWPFTableRow row, CrmOrderEntity item, CrmClientEntity client)
        {
            foreach (var cell in row.GetTableCells())
            {
                var text = cell.GetText().Trim();
                if (text.IsNullOrWhiteSpace())
                {
                    continue;
                }
                switch (text)
                {
                case "{Company:Name}":
                    text = text.Replace(text, AppSettingsHelper.GetString("Company:Name"));
                    break;

                case "{Company:Address}":
                    text = text.Replace(text, AppSettingsHelper.GetString("Company:Address"));
                    break;

                case "{Company:Tel}":
                    text = text.Replace(text, AppSettingsHelper.GetString("Company:Tel"));
                    break;

                case "制单人:{Company: Lister}":
                    text = text.Replace("{Company: Lister}", AppSettingsHelper.GetString("Company:Lister"));
                    break;

                case "NO. {dateTime}":
                case "发货日期:{dateTime}":
                    text = text.Replace("{dateTime}", DateTime.Today.ToString("yyyy-MM-dd"));
                    break;

                case "客户名称:{clientName}":
                    text = text.Replace("{clientName}", client.ClientName);
                    break;

                case "联系人:{clientRealName}":
                    text = text.Replace("{clientRealName}", client.RealName ?? client.ClientName);
                    break;

                case "客户地址:{clientAddress}":
                    var addr = Regex.Replace(item.FullAddress, @"[1]+\d{10}", ""); //手机
                    addr = Regex.Replace(addr, @"(\d{3,4}-)?\d{6,8}$", "");        //座机
                    text = text.Replace("{clientAddress}", addr.Replace(" ", ""));
                    break;

                case "电话:{clientTel}":
                    var tel = Regex.Match(item.FullAddress, @"[1]+\d{10}").Value;           //手机
                    if (tel.IsNullOrWhiteSpace())
                    {
                        tel = Regex.Match(item.FullAddress, @"(\d{3,4}-)?\d{6,8}$").Value;         //座机
                    }
                    text = text.Replace("{clientTel}", tel);
                    break;
                }

                // 为保留模板的格式
                foreach (var para in cell.Paragraphs)
                {
                    for (var i = 0; i < para.Runs.Count; i++)
                    {
                        para.Runs[i].SetText(i == para.Runs.Count - 1 ? text : "", 0);
                    }
                }
            }
        }
コード例 #21
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
                {
                }
            }
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: perfectless/NPOITEST
        /// <summary>
        /// 测试合并单元格
        /// </summary>
        /// <param name="file"></param>
        private void NPOITestMerge(string file)
        {
            #region
            XWPFDocument doc;
            using (FileStream fileread = File.OpenRead(file))
            {
                doc = new XWPFDocument(fileread);
            }
            #endregion

            foreach (XWPFTable table in doc.Tables)
            {
                XWPFTableRow row = table.GetRow(0);

                #region 老版NPOI(2.0)行合并【所有行】
                for (int c = 0; c < row.GetTableCells().Count; c++)
                {
                    XWPFTableCell cell = row.GetTableCells()[c];
                    CT_Tc         tc   = cell.GetCTTc();
                    if (tc.tcPr == null)
                    {
                        tc.AddNewTcPr();
                    }
                    if (c == 0)
                    {
                        tc.tcPr.AddNewHMerge().val = ST_Merge.restart;
                    }
                    else
                    {
                        tc.tcPr.AddNewHMerge().val = ST_Merge.@continue;
                    }
                }
                #endregion

                #region //行合并【0~2列】(有错?)
                //row.MergeCells(0, 2);
                #endregion

                #region //列合并【0~2行】(有错?)
                //for (int r = 0; r < 2; r++)
                //{
                //    XWPFTableCell cell = table.GetRow(r).GetTableCells()[0];
                //    CT_Tc tc = cell.GetCTTc();
                //    if (tc.tcPr == null)
                //    {
                //        tc.AddNewTcPr();
                //    }
                //    if (r == 0)
                //    {
                //        tc.tcPr.AddNewVMerge().val = ST_Merge.restart;
                //    }
                //    else
                //    {
                //        tc.tcPr.AddNewVMerge().val = ST_Merge.@continue;
                //    }
                //}
                #endregion
            }

            #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
        }
コード例 #23
0
ファイル: NPOIWordHelper.cs プロジェクト: ywscr/EasyNPOI
        /// <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);
        }
コード例 #24
0
        /// <summary>
        /// 在下载之前
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private string BeforeDownload(string path, bool includeTable = false)
        {
            string errorMessage = string.Empty;

            try
            {
                byte[] bytes = GetHttpUrlData(path);
                using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length))
                {
                    doc = new XWPFDocument(ms);
                    foreach (XWPFParagraph item in doc.Paragraphs)
                    {
                        if (string.IsNullOrEmpty(item.ParagraphText))
                        {
                            continue;
                        }
                        if (item.ParagraphText.Contains(validSingle))
                        {
                            listParagraph.Add(item);
                        }
                    }
                    for (var tbIndex = 0; tbIndex < doc.Tables.Count; tbIndex++)
                    {
                        XWPFTable tb = doc.Tables[tbIndex];
                        for (var rowIndex = 0; rowIndex < tb.Rows.Count; rowIndex++)
                        {
                            XWPFTableRow         row   = tb.Rows[rowIndex];
                            List <XWPFTableCell> cells = row.GetTableCells();
                            for (var cellIndex = 0; cellIndex < cells.Count; cellIndex++)
                            {
                                XWPFTableCell cell = cells[cellIndex];
                                foreach (XWPFParagraph item in cell.Paragraphs)
                                {
                                    if (string.IsNullOrEmpty(item.ParagraphText))
                                    {
                                        continue;
                                    }
                                    if (item.ParagraphText.Contains(validDouble))
                                    {
                                        listCell.Add(new TableCell()
                                        {
                                            Table      = tb,
                                            TableIndex = tbIndex,
                                            RowIndex   = rowIndex,
                                            CellIndex  = cellIndex,
                                            Cell       = cell,
                                            Paragraph  = item,
                                            CellCount  = cells.Count
                                        });
                                    }
                                    if (item.ParagraphText.Contains(validSingle))
                                    {
                                        listParagraph.Add(item);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                errorMessage = ex.Message;
            }
            return(errorMessage);
        }
コード例 #25
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;
            }
        }